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

180
Vistas
how can i detect if a parent element has a specific child element with javascript?

I have a div that has a "span" and I am dynamically adding "div" tags with a class to identify them, so my question is: how can I know if my parent "div" tag has new div tag children without counting the tag "span"? because my problem is that the e[i].children.length function is always considering the span title as a child

In summary I need to know how many child div tags the parent div has (excluding all other html tags that can be added)

let e = document.getElementsByClassName('classDiv')

for (let i = 0; i < e.length; i++) {

  if (e[i].children.length > 0) {
    console.log("has children");
  } else {
    console.log("has no children");
  }
}
<div id="parent" class="classDiv">
  <span id="title">title</span>
  <div>children1</div>
  <div>children2</div>
  <div>children3</div>
</div>

about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Try

var e = document.querySelectorAll('#parent > div');
console.log(e.length ? "has children" : "has no children");

The > selector is used to select elements with a specific parent

about 4 years ago · Santiago Trujillo Denunciar

0

document.getElementById("parent").getElementsByTagName("div")

Will return all the child elements that are divs.

You can also do the same with getElementsByClassName instead of getElementById, while iterating over the results, and using the same getElementsByTageName on each one.

about 4 years ago · Santiago Trujillo 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