Highlighting Text with JavaScript
This question seeks a JavaScript function capable of highlighting text on a web page, with a specific requirement to highlight only one occurrence of the text. Let's delve into the provided solution and explore how to implement this functionality.
jQuery Highlight Effect
The respondent suggests utilizing the jQuery highlight effect for this task. However, the provided code demonstrates a raw JavaScript implementation that allows for precise highlighting.
JavaScript Implementation
To highlight a specific text, the JavaScript code initializes by identifying the text element within the page. Next, it searches for the target text within the inner HTML of the element. If found, the code dynamically creates a span element with a 'highlight' class around the target text. This span element is then injected back into the page, wrapping the target text and applying the desired highlighting style.
Usage and Caveats
To use the provided code, you need to incorporate the JavaScript and CSS snippets into an HTML document. When you click the button element with the onclick="highlight('fox')" attribute, the code locates and highlights the first occurrence of the word "fox" in the "inputText" div.
It's worth noting that this approach is suitable for smaller text sizes and a single text occurrence. For more extensive highlighting requirements, it might be better to leverage a more comprehensive solution or consider alternative techniques.
The above is the detailed content of How Can JavaScript Highlight Only One Instance of Text on a Web Page?. For more information, please follow other related articles on the PHP Chinese website!