Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 200
fomicz Avatar asked Nov 16 '10 14:11

fomicz


People also ask

How can I select all children of an element except the last child?

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.

How do you find the nth child of an element?

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.

What is the nth child () selector used for?

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.

Which nth child () selector will target only the last list item?

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.


1 Answers

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. – BoltClock

It'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)
like image 61
BoltClock Avatar answered Oct 31 '22 17:10

BoltClock