You do not have to modify the DOM to highlight text in a web page
A Find or Filter field is a indispensable attribute of the web applications visualising text data. When a user searches for a string, it is easy to filter the displayed data but it can be complicated to highlight the matches. Until recently there was only one way — to wrap each match in an additional specifically styled inline element, for example in
i tag. Imagine a web page that displays formatted text:
The text is encoded by a
p tag with two
b tags inside:
If a user searches for string tree is a node, the text in several text nodes has to be wrapped in the marker tag
i is styled by a rule
the searched string will look highlighted in the target text:
Normally users search for short strings that do not have nested tags. Still, if the target text is styled with tags, the search should work with any strings, even those spanning multiple nested elements, which might be complicated to implement.
Since recently, Chrome 105, there is a more straightforward way to style many fragments of displayed text. The new technique does not involve any changes in the DOM and therefore is supposed to be also faster.
The Custom Highlight API
Instead of marker tags, the API uses standard
Range or more performant modern
StaticRange objects to specify the text pieces to be highlighted. The selected fragments get automatically styled according to supplied CSS rules.
Sample web page
I created two sample web pages demonstrating the principal capabilities of the API. Both pages display the same text decorated with many tags. The HTML of the pages is extracted from the DOM specification page source. I borrowed only the
Range-related information and added a script and a style sheet.
The first page https://highlighting.onrender.com/hightlight.html highlights text fragments matching the string entered into the search input. The…