Home > Web Front-end > JS Tutorial > How Can JavaScript Highlight Only One Instance of Text on a Web Page?

How Can JavaScript Highlight Only One Instance of Text on a Web Page?

Barbara Streisand
Release: 2024-12-02 22:08:11
Original
644 people have browsed it

How Can JavaScript Highlight Only One Instance of Text on a Web Page?

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template