How to highlight searched text using JavaScript
📅February 23, 2022
Today we will show you how to highlight the searched text using pure JavaScript code. We can also highlight the text using jQuery library but here we will use the pure JavaScript code.
Checkout more articles on JavaScript
- Capitalize the first letter of a string using JavaScript
- How to set an HTML element’s class using JavaScript
- How to generate a Unique ID in JavaScript
- Add days to a date in JavaScript
- Convert XML to JSON using JavaScript
Let’s use the following JavaScript code to highlight the text.
function highlight(text) {
var inputText = document.getElementById("inputText");
var innerHTML = inputText.innerHTML;
var 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;
}
}
Use the following CSS to highlight the text.
.highlight {
background-color: yellow;
}
Use the following code to highlight the text.
<button onclick="highlight('simply')">Highlight Text</button>
<div id="inputText">
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
</div>
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂