I am trying to highlight any element that has English characters. The code is highlighting the parent elements also. How can I stop this?
Actually, the regular explession is not important. I just need to highlight the single element in any condition. Please only JavaScript not JQuery. Thank you.
HTML
<!DOCTYPE html>
<html>
<body>
<h1>日本</h1>
<div>
<div>日本</div>
<div>1234</div>
</div>
<div>
<div>abcd</div>
<div>日本</div>
</div>
<script>
document.querySelectorAll('*').forEach((ele) => {
let chars = /[a-zA-Z]/;
if(ele.textContent.match(chars)) {
ele.style.border = "3px solid red";
}
});
</script>
</body>
</html>
querySelectorAll('*') will select all elements in the document. The nicest solution would be to pass a selector string that matches only the elements you might want to match - such as div > div, divs which are an immediate child of another div.
.test would also be a tiny bit better (semantically and performance-wise) than .match.
document.querySelectorAll('div > div').forEach((ele) => {
if (/[a-zA-Z]/.test(ele.textContent)) {
ele.style.border = "3px solid red";
}
});
<h1>日本</h1>
<div>
<div>日本</div>
<div>1234</div>
</div>
<div>
<div>abcd</div>
<div>日本</div>
</div>
An approach that would be more general, but more prone to breaking things simply because it's so general, would be to select all text nodes (not elements), and if the node text contains what you're looking for, change the style of their parent element.
function nativeTreeWalker() {
var walker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_TEXT,
null,
false
);
var node;
var textNodes = [];
while(node = walker.nextNode()) {
textNodes.push(node);
}
return textNodes;
}
for (const textNode of nativeTreeWalker()) {
if (/[a-zA-Z]/.test(textNode.textContent)) {
textNode.parentElement.style.border = "3px solid red";
}
}
<h1>日本</h1>
<div>
<div>日本</div>
<div>1234</div>
</div>
<div>
<div>abcd</div>
<div>日本</div>
</div>
As the other answer suggests, you may want to pay attention to text nodes.
Here is example code:
document.querySelectorAll('*').forEach(function (el) {
const cn = el.childNodes;
for (let i = 0; i < cn.length; i++) {-
if (cn[i].nodeName === '#text' && cn[i].data.match(chars)) {
// This el contains text we care about in a text node.
}
}
});
The following snippet will do the job:
function hilite(el,rx){
let n, walk=document.createTreeWalker(el,NodeFilter.SHOW_TEXT,{ acceptNode: n=>rx.test(n.textContent)});
while(n=walk.nextNode()) n.parentElement.classList.add("bold")
}
hilite(document,/[a-zA-Z]/);
.bold {font-weight:900; color:red}
<h1>日本</h1>
<div>
<div>日本</div>
<div>1234</div>
</div>
<div>
<div>abcd</div>
<div>日本<span> and this span too!</span></div>
</div>
The iterable object walk created with document.createTreeWalker() will find all text-nodes matching the specified regular expression rx and will add the class bold to each of their .parentElements.