Don't use innerHTML with a regex, it almost certainly fails for non-trivial content. In addition, there are still differences in how browsers generate it from the live DOM. Replacing innerHTML will also remove all event listeners added as properties of the element (e.g. element.onclick = fn ).
It is best if you can have a string enclosed in an element with an attribute or property that you can search for (id, class, etc.), but searching for text nodes is the best approach.
Edit
Trying to use the general-purpose text highlighting function for an HTML document can lead to a very complex algorithm, because the string can be part of a complex structure, for example:
<h1>Some <span class="foo"><em>s</em>pecial</span> heading</h1>
Finding the string "special heading" is difficult because it is divided into 2 elements. Wrapping it with another element (for example, for highlighting) is also not trivial, since the resulting DOM structure must be valid. For example, text matching “some special” in the above may be wrapped in a span, but not a div.
Any such function should be accompanied by documentation indicating its limitations and the most appropriate use.
Robg
source share