Home > widget-integration > FilterTranslationService > setElementText

FilterTranslationService.setElementText() method

Updates the text content of an HTML element while preserving child elements.

This method finds and updates only text nodes within an element, leaving child HTML elements intact. If no text node exists, it creates one as the first child. Also updates aria-label attributes for accessibility.

Signature:

setElementText(el: HTMLElement | null, newText: string): void;

Parameters

Parameter

Type

Description

el

HTMLElement | null

The HTML element to update, or null (no-op if null)

newText

string

The new text content to set. Should be pre-sanitized if from user input.

Returns:

void

Remarks

The method sanitizes aria-label attributes by prepending "Filter by: " to prevent XSS attacks through attribute injection.

Example 1

Basic usage:

const element = document.querySelector('#filter-label');
this.setElementText(element, 'Color');

Example 2

Extend to add custom element handling:

window.boostWidgetIntegration.extend('FilterTranslationService', (FilterTranslationService) => {
  return class CustomFilterTranslationService extends FilterTranslationService {
    setElementText(el, newText) {
      if (el?.classList.contains('custom-filter')) {
        el.setAttribute('data-original-text', newText);
        el.textContent = `[Custom] ${newText}`;
        return;
      }
      super.setElementText(el, newText);
    }
  };
});