Код: Выделить всё
function highlightMatches() {
const searchTerm = document.getElementById('searchInput').value.trim();
const body = document.body;
removeHighlights(body);
if (!searchTerm) return;
const regex = new RegExp(searchTerm.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'gi');
const walker = document.createTreeWalker(
body,
NodeFilter.SHOW_TEXT, {
acceptNode: function(node) {
if (
node.parentNode && ['SCRIPT', 'STYLE'].includes(node.parentNode.nodeName)
) return NodeFilter.FILTER_REJECT;
return NodeFilter.FILTER_ACCEPT;
}
},
false
);
const nodes = [];
while (walker.nextNode()) {
if (regex.test(walker.currentNode.nodeValue)) {
nodes.push(walker.currentNode);
}
}
nodes.forEach(node => {
const frag = document.createDocumentFragment();
const parts = node.nodeValue.split(regex);
const matches = node.nodeValue.match(regex);
parts.forEach((part, i) => {
frag.appendChild(document.createTextNode(part));
if (matches && i < matches.length) {
const span = document.createElement('span');
span.className = 'highlight';
span.textContent = matches[i];
frag.appendChild(span);
}
});
node.parentNode.replaceChild(frag, node);
});
}
function removeHighlights(root) {
const spans = root.querySelectorAll('span.highlight');
spans.forEach(span => {
span.replaceWith(document.createTextNode(span.textContent));
});
}< /code>
.highlight {
background-color: yellow;
}< /code>
Highlight
paragreaaf 1 sadasdas
Front-end web developer course 2021
Person
Most interest in
Age
Chris
HTML tables
22
Dennis
Web accessibility
45
Sarah
JavaScript frameworks
29
Karen
Web performance
36
Average age
33
This is an example paragraph. Feel free to search any text in this paragraph and it will be highlighted.
Подробнее здесь: https://stackoverflow.com/questions/797 ... -inputs-so