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

136
Visualizações
trying to use query selector to select a specific child in a html document

site i am selecting from looks roughly like this

<div class="start-left">
    ...
    <div class="news-post">...</div>
    <div class="news-post">...</div>
    <!-- want to get this one above -->
    <div class="news-post">...</div>
    <div class="news-post">...</div>
    <div class="news-post">...</div>
    <div class="news-post">...</div>
    ...
</div>

tried this but didnt work on either firefox or chrome

document.querySelector('.start-left div:nth-child(2)')

is this even possible or do i need to rething how i am doing this? I am using puppeteer for a webscraper and need to be able to press a link in a specific news post, e.g the second one

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

nth-child(n) counts all children of the element, regardless of the type of element (tag name). If there are other elements of different type coming before your target element nth-child will fail to find the correct element and may return null.

However, the selector nth-of-type(n)

matches elements based on their position among siblings of the same type (tag name)

and ignores elements of a different type.

// nth-child(2) returns null because the 2nd element is not a div
var wrongElement = document.querySelector('.start-left div:nth-child(2)');
// nth-of-type(2) filters using the type of element
var correctElement = document.querySelector('.start-left div:nth-of-type(2)');
console.log('div:nth-child(2): ' + wrongElement);
console.log('div:nth-of-type(2): ' + correctElement.outerHTML);
<div class="start-left">
    <p class="news-post">...</p>
    <p class="news-post">Not this</p>
    <div class="news-post">...</div>
    <div class="news-post">This one</div>
    <!-- want to get this one above -->
    <div class="news-post">...</div>        
</div>

You could use your work-around by adding the number of preceding elements to the selector, eg nth-child(4), however, a more robust solution is to use nth-of-type(2).

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