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

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

Mary-Kate Olsen
Release: 2024-12-07 13:00:16
Original
239 people have browsed it

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

Highlighing Text with JavaScript

How can you selectively highlight text on a web page using JavaScript? The twist here is to highlight a specific occurrence of a text, instead of every instance as with standard search functionality.

JavaScript Solution

The jQuery highlight effect is a suitable option for highlighting text. However, for a native JavaScript solution, consider the following code:

function highlight(text) {
  const inputText = document.getElementById("inputText");
  const innerHTML = inputText.innerHTML;
  const 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;
  }
}
Copy after login

To complete the implementation, you'll need the following CSS rule:

.highlight {
  background-color: yellow;
}
Copy after login

Usage

Create an HTML file, paste the code, and include an input text field:

<button onclick="highlight('fox')">Highlight</button>

<div>
Copy after login

Click "Highlight" to highlight the first occurrence of "fox" in yellow.

The above is the detailed content of How Can I Highlight a Specific Text Occurrence 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template