Highlight search matches without touching the DOM
Sponsor this newsletter · reach 9,500+ active developers
You add a “filter this page” box to your docs, your FAQ or a long settings screen. The user types “refund”, and now you want every match to light up. The classic fix is to find the text and wrap each match in a <mark>. Then you unwrap them all on the next keystroke, and hope you didn’t break an event listener, a framework’s render, or a word split across two text nodes.
The browser can paint highlights for you now. The CSS Custom Highlight API takes a list of text ranges and styles them, without adding a single element to your page.
The fix
::highlight(search) {
background: #fde047;
color: #000;
}
const content = document.querySelector('article');
const input = document.querySelector('input[type="search"]');
input.addEventListener('input', () => {
const query = input.value.trim().toLowerCase();
const ranges = [];
if (query) {
const walker = document.createTreeWalker(content, NodeFilter.SHOW_TEXT);
while (walker.nextNode()) {
const node = walker.currentNode;
const text = node.textContent.toLowerCase();
let index = text.indexOf(query);
while (index !== -1) {
const range = new Range();
range.setStart(node, index);
range.setEnd(node, index + query.length);
ranges.push(range);
index = text.indexOf(query, index + query.length);
}
}
}
CSS.highlights.set('search', new Highlight(...ranges));
});
The tree walker visits every text node inside the article. For each match, a Range marks where it starts and ends. All the ranges go into one Highlight, registered under the name search, and ::highlight(search) styles them. Your HTML stays exactly as it was.
Can I get a refund?
Yes. If the product doesn't work for you, ask for a refund within 30 days of purchase and we send the full amount back to the original payment method.
How long does the refund take?
Most refunds arrive in 5 to 10 business days. The exact time depends on your bank, not on us.
Can I change my plan later?
You can upgrade or downgrade at any time from the billing page. When you downgrade, the difference is credited to your next invoice instead of refunded.
Do you offer team accounts?
Yes. Invite your team from the settings page. Each member gets their own login, and the owner manages billing for the whole team.
Type “the” or “refund” into the box and watch the matches light up. Press Enter to jump to the next one.
The pieces
Range: a start and an end position inside the page’s text. It doesn’t change anything by itself, it just points at the text.new Highlight(...ranges): a group of ranges that get the same style.CSS.highlights.set('search', ...): registers the group under a name. Setting it again replaces the old matches, and an emptyHighlightclears them. No cleanup code.::highlight(search): styles that group. It acceptscolor,background-color,text-decorationandtext-shadow. No padding, borders or layout, because nothing on the page is allowed to move.
Jump to the next match
A second highlight marks the current match, and Enter moves it:
::highlight(current) {
background: #f97316;
color: #000;
}
let current = -1;
input.addEventListener('keydown', (event) => {
const matches = [...(CSS.highlights.get('search') ?? [])];
if (event.key !== 'Enter' || !matches.length) return;
current = (current + 1) % matches.length;
const active = new Highlight(matches[current]);
active.priority = 1;
CSS.highlights.set('current', active);
matches[current].startContainer.parentElement.scrollIntoView({ block: 'center' });
});
input.addEventListener('input', () => {
current = -1;
CSS.highlights.delete('current');
});
priority = 1 paints the current match on top of the yellow ones. The second input listener resets it, so a new query starts from the first match.
Where it works
- Every current browser: Chrome, Edge, Safari and Firefox all support it. Check
if (CSS.highlights)before using it, and older browsers simply show no highlights. - Screen readers don’t see it: a highlight is paint, not content. Announce the result count in an
aria-liveregion, like “4 matches”, so everyone knows what happened. - One text node at a time: a match split across elements, like
re<b>fund</b>, won’t be found. For search boxes, that is almost never a problem. - Big pages: walking thousands of text nodes on every keystroke adds up. Debounce the input and it stays smooth.
Where this comes up
- Docs and FAQs: a “filter this page” box that shows where the answer is.
- Long settings screens: type “email” and see every related option.
- Tables and logs: spot every occurrence of an ID or an error code.
- Command palettes: highlight the matching part of each result in your Cmd+K menu.
Why this matters
- Your DOM stays untouched: no wrapping, no unwrapping, no broken event listeners or framework renders.
- It’s fast: the browser only repaints. Nothing is re-laid out, because nothing on the page moves.
- Clearing is one line: set an empty highlight, and every match is gone.
Find the longest page in your app, add a search box on top, and paste in the fix. Your users will find answers before they think of contacting support.
Happy coding!
Marko