How to search and highlight text in HTML page from varies elements (not just one) using vanilla javascript?

2 min read 04-10-2024
How to search and highlight text in HTML page from varies elements (not just one) using vanilla javascript?


Searching and Highlighting Text Across Multiple HTML Elements with Vanilla JavaScript

Finding specific text within a webpage and highlighting it is a common task in web development. While it's simple to do with a single element, searching across multiple elements with vanilla JavaScript can be a little trickier. This article will walk you through the process, providing a clear, step-by-step guide with explanations and examples.

The Problem: Searching Across Multiple Elements

Imagine you have a webpage with various sections, like a blog post with multiple paragraphs, headings, and quotes. You want users to be able to search for a specific term and have all occurrences highlighted across all these elements. Let's break down how we can achieve this using plain JavaScript.

The Solution: Vanilla JavaScript Search and Highlight

Here's a basic JavaScript code snippet that accomplishes the task:

function highlightText() {
  const searchTerm = document.getElementById('searchInput').value.toLowerCase();
  const elements = document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, blockquote'); // Select elements to search

  elements.forEach(element => {
    const text = element.textContent.toLowerCase();
    if (text.includes(searchTerm)) {
      const regex = new RegExp(searchTerm, 'gi'); // Case-insensitive and global match
      const newText = text.replace(regex, `<span class="highlight">${searchTerm}</span>`);
      element.innerHTML = newText;
    }
  });
}

// Example usage:
document.getElementById('searchButton').addEventListener('click', highlightText);

Explanation:

  1. Get the Search Term: We retrieve the search term from an input field (searchInput) and convert it to lowercase for case-insensitive matching.

  2. Select Elements: We use querySelectorAll to grab all elements with tags like paragraphs (p), headings (h1 through h6), and blockquotes (blockquote). This allows us to search through various content blocks.

  3. Iterate and Check: We loop through each selected element using forEach. For each element, we grab its text content and convert it to lowercase for comparison.

  4. Apply Regex and Highlight: If the element's text contains the search term, we use a regular expression with the gi flag (global and case-insensitive) to find all occurrences. We then replace each occurrence with a <span> tag with a class "highlight" to apply visual styling.

  5. Update Inner HTML: We update the element's innerHTML with the modified text, effectively highlighting the search term within the element.

Additional Enhancements

  • Styling: Add CSS rules for the .highlight class to define how the highlighted text should appear (e.g., yellow background, bold font).

  • Clear Highlights: Implement a function to clear all existing highlights when the search term is cleared or a new search is performed.

  • Input Validation: Add checks to handle empty search terms or potentially problematic inputs.

Importance of Accessibility

Remember to consider accessibility when highlighting text. Ensure that the chosen color contrast for highlighting is sufficient for users with visual impairments. Users might prefer a different method of highlighting, like a visual indicator next to the highlighted word.

Conclusion

This code provides a foundation for creating a simple text search and highlight feature on your webpage. It demonstrates how to efficiently target multiple elements and use regular expressions for case-insensitive and global replacements. By customizing the code and incorporating additional enhancements, you can create a user-friendly search experience that enhances the usability of your web application.