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

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

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