Jason Liu
Jason Liu

Reputation: 31

How do I select nth element in a given set

How do I select first span, second span or last span for the following html?

<div>
    <b>Text<b/>
    <span></span>
    <span></span>
    <span></span>
</div>

How can I select the nth element in a given set?

Upvotes: 1

Views: 1899

Answers (3)

codeuix
codeuix

Reputation: 1396

The :nth-child selector allows you to select one or more elements based on their source order, according to a formula

The formula is constructed using the syntax an+b, where:

"a" is an integer value
"n" is the literal letter "n"
"+" is an operator and may be either "+" or "-"
"b" is an integer and is required if an operator is included in the formula

Here are some ways you can achieve this as per your requirement:

div span:first-child {

}
div span:nth-child(an+b) {

}
div span:last-child {

}

Here are some other relative properties you can use as well:

  • nth-last-child
  • nth-of-type
  • nth-last-of-type
  • first-of-type
  • last-of-type

Upvotes: 0

ATIQ UR REHMAN
ATIQ UR REHMAN

Reputation: 448

use n-th child if i make that code for example in this way i Specify background color is blue for every

tag element that is the second child of it parent is:

p:nth-child(2) {
background: blue;
}

Upvotes: 0

SoKeT
SoKeT

Reputation: 610

Use the nth-child selector:

span:nth-child(2) {}

This selects the first span since it's the second child. If you want to select the second span, you can use this instead:

span:nth-of-type(2) {}

You can also use first-child, last-child, nth-child(odd) or nth-child(even), among others.

Upvotes: 3

Related Questions