Highlighing Text with JavaScript
How can you selectively highlight text on a web page using JavaScript? The twist here is to highlight a specific occurrence of a text, instead of every instance as with standard search functionality.
JavaScript Solution
The jQuery highlight effect is a suitable option for highlighting text. However, for a native JavaScript solution, consider the following code:
function highlight(text) { const inputText = document.getElementById("inputText"); const innerHTML = inputText.innerHTML; const index = innerHTML.indexOf(text); if (index >= 0) { innerHTML = innerHTML.substring(0, index) + "<span class='highlight'>" + innerHTML.substring(index, index + text.length) + "</span>" + innerHTML.substring(index + text.length); inputText.innerHTML = innerHTML; } }
To complete the implementation, you'll need the following CSS rule:
.highlight { background-color: yellow; }
Usage
Create an HTML file, paste the code, and include an input text field:
<button onclick="highlight('fox')">Highlight</button> <div>
Click "Highlight" to highlight the first occurrence of "fox" in yellow.
The above is the detailed content of How Can I Highlight a Specific Text Occurrence on a Web Page Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!