javascripthtmlmarkupdomparser

Within a markup-string, how to replace any e.g. class-name specified element with its own title-text?


I have a variable called $text.

I want to make it so that if there are any spans with the class "emote", replace the entire span and its contents with the title attribute of the span. Also, it must be case sensitive.

If $text had this as a value:

<p>blah blah blah <span class="emote" title="bOOger"> blah blah blah</span></p>

It would become this:

<p>blah blah blah bOOger</p>

How could I achieve this?


Solution

  • function replaceAnyTargetedElementByItsTitleText(markup, selector) {
      const doc = (new DOMParser)
        .parseFromString(markup, "text/html");
    
      doc
        .body
        .querySelectorAll(selector)
        .forEach(node => node
          .parentNode
          .replaceChild(
            document.createTextNode(node.title),
            node,
          )
        );
    
      return doc.body.innerHTML;
    }
    
    const markupBefore =
      '<p>foo bar baz <span class="emote" title="bOOger">quick brown fox</span></p>';
    
    const markupAfter =
      replaceAnyTargetedElementByItsTitleText(markupBefore, '.emote');
    
    console.log({ markupBefore, markupAfter });
    .as-console-wrapper { min-height: 100%!important; top: 0; }