0

I'm writing JavaScript code that highlights text in the current document, but I don't control the document contents, so I need to be able to deal with any arbitrary HTML.

So when I've found a Text DOM node, I want to replace it with a <span> element containing the text.

The problem is, while this is OK to do in most places, there are contexts where a Text node can occur but a <span> element cannot. The following come to mind: <style>, <script>, <title>, <option>, <svg>, but there are surely more. (I believe the HTML standard's "Content model" section for each element is the pertinent source; see this example.) So I assume if I replaced Texts with <span> elements in these contexts, it would violate some well-formedness rule and could lead to undesirable behavior.

How do I check whether or not a given Text node can be replaced with a span?

Jo Liss
  • 30,333
  • 19
  • 121
  • 170
  • I don't think any of those elements support highlighting a selection, so the problem doesn't come up. If you can highlight the text, I think you should be able to replace it with a span. – Barmar May 24 '23 at 15:52
  • @Barmar I'm not going off the user's text selection -- the text to highlight is determined programmatically, so it could conceivably be any Text in the DOM. – Jo Liss May 24 '23 at 16:25

0 Answers0