How to highlight searched text using JavaScript
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
Let’s use the following JavaScript code to highlight the text.
1 2 3 4 5 6 7 8 9 | 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.
1 2 3 | .highlight { background-color: yellow; } |
Use the following code to highlight the text.
1 2 3 4 5 | <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..!! đŸ™‚