skip to Main Content

In my vue app I have a method to search for words in the DOM and scroll to first result, however I also want to highlight the found word in the DOM, how can I do this?

My search method:

search() 
    { 
        const matches = document.querySelectorAll("body*:not(script):not(style):not(title)"); 

        for (let i = 0; i < matches.length; i++) 
        { 
        const element = matches[i]; 
        if (element.textContent.includes(searchTerm)) 
        { 
            if(i == 0)
            {
                element.scrollIntoView();
            }
            console.log('Found'); 
        } 
    } 

Thanks in advance

2

Answers


  1. I think you could simply use inline CSS for that:

    function search(searchTerm) { 
        const matches = document.querySelectorAll("p"); 
    
        for (let i = 0; i < matches.length; i++) { 
            const element = matches[i]; 
    
            if (element.textContent.includes(searchTerm)) { 
                if (i == 0) {
                    element.scrollIntoView();
                }
                console.log('Found'); 
            }
    
            /* Highlight substring */
            element.innerHTML = element.innerHTML.replace(searchTerm, `<span style='background-color: #FFFF00'>${searchTerm}</span>`)
        }
    }```
    
    Login or Signup to reply.
  2. I think this solution should work for you.

    const searchTerm = 'example';
    const matches = document.querySelectorAll('body *:not(script):not(style):not(title)');
    let firstMatch = null;
    
    for (let i = 0; i < matches.length; i++) {
      const node = matches[i];
      const nodeText = node.textContent;
    
      if (nodeText.includes(searchTerm)) {
        const newNodeText = nodeText.replace(new RegExp(searchTerm, 'g'), `<span class="highlight">${searchTerm}</span>`);
        node.innerHTML = newNodeText;
        if (firstMatch === null) {
          firstMatch = node;
        }
      }
    }
    
    if (firstMatch !== null) {
      firstMatch.scrollIntoView({ behavior: 'smooth', block: 'center' });
    }
    

    For CSS highlight class

    .highlight {
      background-color: yellow;
      color: black;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search