I’ve a structure like this:
<div>
<a></a>
<p></p>
<p></p>
</div>
And I have all p’s already in a real array:
var p = [].slice.call( document.querySelectorAll('div p') );
I could grab the first item with p[0] but I need the first-child (which in this case is the same) so I tried querySelectorAll but I get no results doing this:
p.forEach(function( el ) {
console.log( el.parentNode.querySelectorAll('p:first-child') ) //=> empty
});
If I do el.parentNode.querySelectorAll(':first-child') I get the <a> which is not what I want. How do I filter the first-child p’s in my array?
Edit: I tried creating a dummy element and recreating the structure with clones to find my element, although it kinda works I’m not sure it’s the best idea…
There’s a
first-of-typepseudo-class in CSS3. I don’t think it’s very widely supported. Thefirst-childpseudo class is a predicate that selects elements of any type that are the first things in their parents child node lists. Because the<a>comes first, it’s the only thing that’d “hit” with:first-child.edit — whoa actually
:first-of-typeseems to be pretty well supported now, according to caniuse.