The Power of Modern APIs
This demonstration utilizes the modern CSS Custom Highlight API to provide non-destructive text highlighting. Unlike older methods that wrap text in HTML elements like <mark>, this new API works without altering the DOM structure. This is a huge advantage because it keeps the original HTML clean and doesn't interfere with other scripts or frameworks like React or Vue.
The core idea is to use JavaScript to define arbitrary text Range objects and then style them using a new CSS pseudo-element, ::highlight(). This approach is not only cleaner but also significantly more performant, as the browser's rendering engine handles the heavy lifting.
Code Example: JavaScript
Let's look at a typical JavaScript function. You can try searching for terms like const, function, return, or even =>.
const processData = (data) => {
if (!data || data.length === 0) {
// This is an important edge case to handle.
console.warn("Warning: Data is empty.");
return null;
}
// A complex data transformation.
const result = data
.map(item => item * 2)
.filter(item => item > 10);
return result;
};
// Example of how the DOM is used for highlighting.
const element = document.getElementById('content');
const searchTerms = ['dom', 'css'];
// The highlight function would then process this.
Styling with CSS
The highlights themselves are styled with pure CSS. The API introduces a new named highlight concept. For example, a search result might be a 'search-term' highlight.
/* This is how you style a highlight named 'search-term' */
::highlight(search-term) {
background-color: yellow;
color: black;
text-decoration: underline;
text-decoration-color: red;
}
This separation of concerns makes the system incredibly flexible. You can define different types of highlights for different purposes (e.g., search results, validation errors, comments) and style them all independently in your CSS, just like any other element.
Performance at Scale
Performance is a key feature. Because we are not manipulating the DOM with thousands of new elements, the browser remains fast and responsive. A TreeWalker is used to efficiently traverse the DOM, looking only at text nodes and skipping elements like <script> or <style>. This ensures that even on very large documents, the highlighting process is quick and doesn't freeze the user interface. The entire process is designed to be efficient and scalable.