How can I select an nth child without knowing the parent element?
I can't figure out a way of selecting the nth element, last element, or first element in cases where I don't know the parent element. nth-child
exists, but only for children, for example:
<div>
<p>One</p>
<p>Two</p>
</div>
p:last-child
selects the "Two" paragraph, and p:first-child
selects the "One" paragraph. But what about when I have dynamic code and have no idea what the parent name is, or even what the parent really is (may be a div, span, anchor, ul, etc.)?
For example:
<youdontknowwhat!>
<p class="select-me">One</p>
<p class="select-me">Two</p>
</youdontknowwhat!>
How do I select the second paragraph here? (I'm unable to select youdontknowwhat!
since I really don't know what element it is (it's just a hypothetical name).
Why are there first-child
, last-child
, and nth-child
selectors and NO :first
, :last
, :nth
(like .select-me:first
)?
Solution 1:
How would
:first
be different from:first-child
? Every HTML element is a child of some other element in the DOM except<html>
which is the root element. – BoltClockIt'd be since you don't know the parent element. – fomicz
You don't need to know the parent element for :first-child
or :nth-child()
to work. They will just work, even if you don't specify the parent element.
The following selector is guaranteed to match any appropriate .select-me
element regardless of what its parent element is:
.select-me:nth-child(2)
Solution 2:
* p:nth-child(2)
of course it's better if you can specify the parent selector (for a matter of performance)