site i am selecting from looks roughly like this
<div >
...
<div >...</div>
<div >...</div>
<!-- want to get this one above -->
<div >...</div>
<div >...</div>
<div >...</div>
<div >...</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
CodePudding user response:
For anyone else who has the same problem, it might be because of the other stuff above. Just add however many items above the children there are to the nth child slector.
example: to get the second one when there are two other things above the children, add two to the selector
CodePudding user response:
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 >
<p >...</p>
<p >Not this</p>
<div >...</div>
<div >This one</div>
<!-- want to get this one above -->
<div >...</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).
