Recipe 17.1
Highlighting Text Ranges
Compatibility Note: Highlight API
This feature may not be supported on all browsers yet. Please check the latest compatibility data before using in a production application.
Browser support for Highlight APIYou can use the CSS Custom Highlight API to highlight arbitrary ranges of text in the document. There are three general steps to do this:
- Create a
Range
object that contains the text you want to highlight. - Register the highlighted range with the API under a unique name.
- Use the
highlight
pseudo-element to apply the styles you want to the highlight, referencing the name.
Demo
This is some text. We're using the CSS Custom Highlight API to highlight some of the text.
Code
JavaScript
function getRange(textNode, textToHighlight) {
const startOffset = textNode.textContent.indexOf(textToHighlight);
const endOffset = startOffset + textToHighlight.length;
// Create a Range for the text to highlight
const range = new Range();
range.setStart(textNode, startOffset);
range.setEnd(textNode, endOffset);
return range;
}
const node = document.querySelector('#text');
const range = getRange(node.firstChild, 'highlight some of the text');
// Register the CSS highlight
const highlight = new Highlight(range);
CSS.highlights.set('highlight-range', highlight);
HTML
<style>
::highlight(highlight-range) {
background-color: #fef3c7;
}
</style>
<p id="text">
This is some text. We're using the CSS Custom Highlight API to highlight some of the text.
</p>