Search code examples
javascripthtmlinnerhtml

Can I replace HTML text in an element by using vanilla JS as so? e.target.innerHTML.replace('old text', 'new text');


const tour = document.querySelector('.tour__heading');
const addSection = e => {
        e.target.innerHTML.replace('SHOW','red');
};
tour.addEventListener('click', addSection);

Can I use e.target to change HTML text as above?


Solution

  • The String.prototype.replace function will replace the content of a string but not modify the original.

    You can either do:

    e.target.innerHTML = e.target.innerHTML.replace('SHOW','red')
    

    Or you can create a polyfill for a custom function on the HTMLElement object.

    /* A polyfill for a custom HTML text replacer function */
    if (HTMLElement.prototype.replaceHTML === undefined) {
      HTMLElement.prototype.replaceHTML = function(regexpOrSubstr, newSubstrOrFunc) {
        this.innerHTML = this.innerHTML.replace.apply(this.innerHTML, arguments)
      }
    }
    
    const tour = document.querySelector('.tour__heading')
    const addSection = e => {
      //e.target.innerHTML = e.target.innerHTML.replace('SHOW','red')
      e.target.replaceHTML('SHOW','red')
    }
    tour.addEventListener('click', addSection)
    .tour__heading:hover {
      cursor: pointer;
    }
    <div class="tour__heading">SHOW</div>


    Update

    A preferable approach is to avoid polluting the prototype. The optimal method for achieving this involves leveraging functional programming principles. Rather than adding a method to each DOM Element individually, a more effective strategy is to pass the Element as an argument to a function.

    Here is a modern function (JSDoc included) that replaces the inner HTML of an element and returns the modified object:

    /**
     * Replaces the innerHTML of a given DOM element based on a specified pattern
     * and replacement.
     *
     * @param {Element} element - The target DOM element to modify.
     * @param {String|RegExp} pattern - The search pattern to match within the
           innerHTML.
     * @param {String|Function} replacement - The string or function used for
           replacement.
     *     If a function, it receives the matched substring and should return the
     *     replacement string.
     * @return {Element} The original modified element with updated innerHTML.
     */
    const replaceHTML = (element, pattern, replacement) => {
      const { innerHTML } = element;
      return Object.assign(element, {
        innerHTML: innerHTML.replace(pattern, replacement)
      });
    };
    
    document.querySelector('.click-me')
      .addEventListener('click', e => {
        replaceHTML(e.target, /\b(?:really)\b/g, 'very')
      })
    .click-me:hover {
      cursor: pointer;
    }
    <h2 class="click-me">A really really really long title</h2>