Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

88
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda