Home > Web Front-end > JS Tutorial > How Can I Highlight a Single Instance of Text in JavaScript?

How Can I Highlight a Single Instance of Text in JavaScript?

DDD
Release: 2024-12-04 11:16:09
Original
842 people have browsed it

How Can I Highlight a Single Instance of Text in JavaScript?

Highlight Text with JavaScript

Highlighting specific text on a web page can enhance user experience and draw attention to important content. This demonstration focuses on a single-occurrence highlighting, unlike the typical highlight effect that identifies all instances of the text, which is commonly used in search functionality.

jQuery Highlight Effect

For a quick and easy solution, the jQuery highlight effect can be employed:

$(selector).highlight(text, options);
Copy after login

Simply specify the text and highlight options to achieve your desired result.

Custom JavaScript Code

If you prefer a raw JavaScript approach, consider this code snippet:

function highlight(text) {
  // Get the target element
  var inputText = document.getElementById("inputText");

  // Extract the element's HTML content
  var innerHTML = inputText.innerHTML;

  // Locate the first occurrence of the text
  var index = innerHTML.indexOf(text);

  // Check if text is found
  if (index >= 0) { 
    // Inject highlight markup around the matching text
    innerHTML = innerHTML.substring(0, index) + "<span class='highlight'>"
                + innerHTML.substring(index, index + text.length) + "</span>"
                + innerHTML.substring(index + text.length);

    // Update the element with highlighted text
    inputText.innerHTML = innerHTML;
  }
}
Copy after login

Don't forget to add the corresponding CSS style for the 'highlight' class:

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

Usage Example

To highlight the word "fox" in a specific div element, simply invoke the highlight function:

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

<div>
Copy after login

Clicking the button will highlight the first occurrence of "fox" in yellow.

The above is the detailed content of How Can I Highlight a Single Instance of Text in 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