8.5 · Typography & shape
Style text ranges: the Custom Highlight API
Style any text range, like search matches, without wrapping it in elements.
Highlighting search results or spelling errors used to mean wrapping
words in <mark> or <span>, which
changes the DOM and gets slow on large documents. The Custom Highlight
API registers Range objects under a name instead:
CSS.highlights.set('search', new Highlight(...ranges)).
CSS styles them with ::highlight(search). Only a few
properties apply, mainly color, background and text decoration. The
playground editor on this site uses the same API for its syntax
colors.
// Wrap every match in an element
text.innerHTML = text.textContent.replace(
/css/gi,
'<mark>$&</mark>',
)
CSS.highlights.set('search',
new Highlight(...ranges))
::highlight(search) {
background-color: gold;
}