Recipe 17.1

Highlighting Text Ranges

You can use the CSS Custom Highlight API to highlight arbitrary ranges of text in the document. There are three general steps to do this:

  1. Create a Range object that contains the text you want to highlight.
  2. Register the highlighted range with the API under a unique name.
  3. 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>
Web API Cookbook
Joe Attardi