1

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?

Peter Seliger
  • 11,747
  • 3
  • 28
  • 37
Felix
  • 2,532
  • 5
  • 37
  • 75
  • 2
    Which approach would the author choose? Is there already any code which shows what the OP did try? Also the chosen text within before and after makes the goal a little ambiguous. – Peter Seliger May 25 '22 at 18:33
  • @PeterSeliger regex might be a solution? But I don't know regex at all. – Felix May 25 '22 at 18:36
  • How about [`DOMParser.parseFromString`](https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString)? jQuery actually is not needed. – Peter Seliger May 25 '22 at 18:38
  • Convert it to a DOM element via [`.parseFromString`](https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString) and then perform HTML manipulation on that: [Create a text node](https://developer.mozilla.org/en-US/docs/Web/API/Document/createTextNode), insert it after the span, then remove the span. – Ouroborus May 25 '22 at 18:39
  • Convert to DOM element as others have noted, then use the answers to [JS. How to replace html element with another element/text, represented in string?](https://stackoverflow.com/q/13388379/215552) – Heretic Monkey May 25 '22 at 18:42

1 Answers1

0

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; }
Peter Seliger
  • 11,747
  • 3
  • 28
  • 37