Home > Web Front-end > JS Tutorial > How Can I Create a One-Time Text Highlighting Effect with JavaScript?

How Can I Create a One-Time Text Highlighting Effect with JavaScript?

Barbara Streisand
Release: 2024-12-04 17:15:12
Original
612 people have browsed it

How Can I Create a One-Time Text Highlighting Effect with JavaScript?

Highlighting Text with JavaScript: A One-Time Spotlight

When it comes to highlighting text in a web page, we often resort to default browser functionality. However, what if you need a precise and one-time highlighting effect? Here's how you can achieve it using JavaScript.

The jQuery highlight effect provides a straightforward solution for text highlighting. But if you're seeking a raw JavaScript approach, consider the following code snippet:

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 match our highlighting effect with the text we want to highlight, we apply some CSS rules:

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

Now, let's put it all together. We create an HTML element with the ID "inputText" where we want the highlighting to take place. We also add a button with the onclick event that triggers the "highlight" function.

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

<div>
Copy after login

By clicking the "Highlight" button, the JavaScript code locates the first occurrence of "fox" in the text and encloses it within a element with the class "highlight." This span element applies the yellow background color, making the "fox" text stand out.

This code sample provides a simple yet effective method for highlighting text in a web page. You can customize the search text, highlight color, or even extend the functionality to highlight multiple occurrences if needed.

The above is the detailed content of How Can I Create a One-Time Text Highlighting Effect with 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