Home > Web Front-end > JS Tutorial > How Can I Highlight Text on a Web Page Using JavaScript?

How Can I Highlight Text on a Web Page Using JavaScript?

DDD
Release: 2024-12-08 11:18:12
Original
895 people have browsed it

How Can I Highlight Text on a Web Page Using JavaScript?

Highlighting Text with JavaScript

Highlighting text on a web page is a useful feature for emphasizing important information or drawing attention to specific content. While various techniques exist, this article explores a simple JavaScript implementation:

Code Snippet:

The provided JavaScript function, highlight(), effectively highlights the first occurrence of a specified text within a given HTML element (e.g., a paragraph). Here's how it works:

  1. The function takes a single argument (text) as the substring to be highlighted.
  2. It retrieves the input text from the HTML element with the ID "inputText".
  3. It calculates the index where the text occurs within the input text.
  4. If the text is found, it wraps the found instance with a "" element containing a "highlight" class, which is defined in the CSS section.

Example Usage:

To utilize this function, include the JavaScript code in your HTML document and attach an onClick event to a button or link. When clicked, the event will trigger the function call, passing the text to be highlighted as a parameter. For instance:

<button onclick="highlight('fox')">Highlight</button>
<div>
Copy after login

In this example, clicking the button will highlight the first occurrence of the word "fox" in the "inputText" element.

CSS Customization:

You can further customize the highlighted appearance by overriding the styles for the "highlight" class in your CSS. The given example applies a yellow background color to the highlighted text, but you can tweak it to suit your design needs.

By applying these techniques, you can easily highlight specific text on a web page, enabling users to quickly locate and focus on important information.

The above is the detailed content of How Can I Highlight Text on a Web Page Using JavaScript?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template