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
Mary-Kate OlsenOriginal
2024-12-07 13:00:16267browse

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;
  }
}

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

.highlight {
  background-color: yellow;
}

Usage

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

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

<div>

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!

Statement:
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