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

91
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 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