You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
constquery=document.getElementById("query");constarticle=document.querySelector("article");// Find all text nodes in the article. We'll search within// these text nodes.consttreeWalker=document.createTreeWalker(article,NodeFilter.SHOW_TEXT);constallTextNodes=[];letcurrentNode=treeWalker.nextNode();while(currentNode){allTextNodes.push(currentNode);currentNode=treeWalker.nextNode();}// Listen to the input event to run the search.query.addEventListener("input",()=>{// If the CSS Custom Highlight API is not supported,// display a message and bail-out.if(!CSS.highlights){article.textContent="CSS Custom Highlight API not supported.";return;}// Clear the HighlightRegistry to remove the// previous search results.CSS.highlights.clear();// Clean-up the search query and bail-out if// if it's empty.conststr=query.value.trim().toLowerCase();if(!str){return;}// Iterate over all text nodes and find matches.constranges=allTextNodes.map((el)=>{return{ el,text: el.textContent.toLowerCase()};}).map(({ text, el })=>{constindices=[];letstartPos=0;while(startPos<text.length){constindex=text.indexOf(str,startPos);if(index===-1)break;indices.push(index);startPos=index+str.length;}// Create a range object for each instance of// str we found in the text node.returnindices.map((index)=>{constrange=newRange();range.setStart(el,index);range.setEnd(el,index+str.length);returnrange;});});// Create a Highlight object for the ranges.constsearchResultsHighlight=newHighlight(...ranges.flat());// Register the Highlight object in the registry.CSS.highlights.set("search-results",searchResultsHighlight);});
Very nice. But it currently doesn't match our browser support criteria (chrome/edge >= 88, firefox >= 78, safari >= 14). In future, we might replace mark.js with it 👀 Keeping this open for now.
Is your feature request related to a problem? Please describe.
Highlighting search results keywords using string replacement is outdated
Describe the solution you'd like
Native API
CSS.highlights
https://developer.mozilla.org/en-US/docs/Web/API/CSS_Custom_Highlight_API
css
Describe alternatives you've considered
No response
Additional context
No response
Validations
The text was updated successfully, but these errors were encountered: