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

90
Vistas
How to find the first child that has a certain class in a DOM subtree?

Is there any DOM method to find the first element that has a certain class

<div class="parent">
   <div>
      <div></div>
      <p class="paragraph"></p>
  </div>
</div>

what if i have multiple p elements in the page and i need only to find the p element that is anywhere in the subtree starting from .parent.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

const parents = document.querySelectorAll('.parent');

if (parents) {
  parents.forEach((parent, index) => {
    const children = parent.querySelectorAll('.paragraph');
    children[0].style.color='#f00';
    children[0].style.textDecoration = 'underline';
    console.log((children ? children.length : 'No') + ` instances of paragraph class in parent ${index}`);
  });
} else {
  console.warn('no soup for you.')
}

// Or if you're just wanting to grab them all in one.
const parents2 = document.querySelectorAll('.parent .paragraph');
console.log(`There's ${parents2.length} instances of .parent .paragraph class in the document total.`);
console.log(`The first instance found is ${parents2[0]}`);
<div class="parent">
   <div>
      <div></div>
      <p class="paragraph">TEST</p>
  </div>
  <div>
      <div></div>
      <p class="paragraph">TEST</p>
  </div>
  <div>
      <div></div>
      <p class="paragraph">TEST</p>
  </div>
  <div>
      <div></div>
      <p class="paragraph">TEST</p>
  </div>
</div>
<div class="parent">
  <div>
      <div></div>
      <p class="paragraph">TEST2</p>
  </div>
  <div>
      <div></div>
      <p class="paragraph">TEST2</p>
  </div>
  <div>
      <div></div>
      <p class="paragraph">TEST2</p>
  </div>
</div>

about 4 years ago · Juan Pablo Isaza Denunciar

0

document.querySelector('.parent p.paragraph')

Will return at most one p element with the paragraph class that has an element with the parent class as an ancestor. It may return undefined if there are no elements matching that description. If there are multiple that match that description, it will return only one, the “first” as JavaScript defines it. Whether JavaScript’s idea of the “first” is the same as yours or not it’s unclear, since you haven’t defined which would be “first” in your question. As MDN puts it,

Note: The matching is done using depth-first pre-order traversal of the document's nodes starting with the first element in the document's markup and iterating through sequential nodes by order of the number of child nodes.

That means if you have this

var paragraph = document.querySelector('.parent p.paragraph');
console.log(paragraph.innerText);
<div class="parent">
  <div>
    <div>
      <div>
        <p class="paragraph">First</p>
      </div>
    </div>
  </div>
  <p class="paragraph">Second</p>
</div>

It will print “First” in the console, not “Second,” as that element is the one paragraph is set to because querySelector searches down through the divs first (depth-first).

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