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?