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>`)
}
}```
- [Vuejs]-V-model keeps showing the same data in vuejs
- [Vuejs]-How can I implement Vue 3's built in KeepAlive component to cache a child component of a page so that it only calls it's API on first page load
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;
}
- [Vuejs]-Fancybox 5 not show PDF file
- [Vuejs]-VueJS 3.x composition API: why is v-model property conveyed to component empty?
Source:stackexchange.com