JAVASCRIPT

Highlight Search Term Occurrences within a DOM Element

Implement a JavaScript function to find and highlight all occurrences of a specific search term within the text content of any HTML element, useful for search features.

function highlightText(elementId, searchTerm, className = 'highlight') {
    const element = document.getElementById(elementId);
    if (!element || !searchTerm) {
        console.warn('Element not found or search term is empty.');
        return;
    }

    const regex = new RegExp(`(${searchTerm})`, 'gi');
    const textNodes = [];

    function collectTextNodes(node) {
        if (node.nodeType === Node.TEXT_NODE) {
            textNodes.push(node);
        } else {
            for (const child of node.childNodes) {
                collectTextNodes(child);
            }
        }
    }

    collectTextNodes(element);

    textNodes.forEach(node => {
        const originalText = node.textContent;
        if (originalText.match(regex)) {
            const fragment = document.createDocumentFragment();
            const parts = originalText.split(regex);

            parts.forEach(part => {
                if (part.toLowerCase() === searchTerm.toLowerCase()) {
                    const span = document.createElement('span');
                    span.className = className;
                    span.textContent = part;
                    fragment.appendChild(span);
                } else {
                    fragment.appendChild(document.createTextNode(part));
                }
            });
            node.parentNode.replaceChild(fragment, node);
        }
    });
    console.log(`Highlighted all occurrences of '${searchTerm}' in element ID '${elementId}'.`);
}

// Example Usage:
// HTML: <p id="myParagraph">This is a sample text for highlighting purposes. Sample text everywhere!</p>
// highlightText('myParagraph', 'sample', 'search-highlight');
// CSS: .search-highlight { background-color: yellow; font-weight: bold; }
How it works: This advanced snippet demonstrates how to highlight all occurrences of a given `searchTerm` within a specified DOM element. It recursively collects all text nodes, then uses a regular expression to split the text. For each part matching the `searchTerm`, it wraps it in a `<span>` with a customizable `className` (e.g., 'highlight'), otherwise, it re-inserts the original text. A `DocumentFragment` is used for efficient replacement of the original text node, minimizing reflows. This is crucial for implementing search and highlight functionalities.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs