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
)?
When designing and developing web applications, sometimes we need to select all the child elements of an element except the last element. To select all the children of an element except the last child, use :not and :last-child pseudo classes.
Use the querySelector() method to get the nth child of an element, e.g. document. querySelector('#parent :nth-child(3)') . The :nth-child pseudo class returns the element that matches the provided position. Here is the HTML for the examples in this article.
The :nth-child selector allows you to select one or more elements based on their source order, according to a formula. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling elements.
The :nth-last-child(n) selector matches every element that is the nth child, regardless of type, of its parent, counting from the last child.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With