Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

89
Visualizações
Only highlight elements without parents in JavaScript

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>
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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>

about 4 years ago · Juan Pablo Isaza Relatório

0

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.
        }
    }
});
about 4 years ago · Juan Pablo Isaza Relatório

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda