[Vuejs]-Highlighting words found on DOM

0๐Ÿ‘

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>`)
    }
}```

0๐Ÿ‘

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

Leave a comment