how to select nth item from a CSS selector

Viewed 979
[data-short-caption="itemName" i] .circle-base, 

this selector is identifying two items in the DOM, I need to select the second item, is there any way like we have in xpath to select the second item ?

The HTML Structure is something like this :

<div class="selection" data-select-item="select-item">
    <div data-short-caption='itemName'>
      <div class=circle-base> </div>
    </div>
    
    <div data-short-caption='itemName'>
     <div class=circle-base> </div>
    </div>
</div>
2 Answers

As per the HTML:

<div class="selection" data-select-item="select-item">
    <div data-short-caption='itemName'>
      <div class=circle-base> </div>
    </div>

    <div data-short-caption='itemName'>
     <div class=circle-base> </div>
    </div>
</div>

To identify only the second item you can use either of the following based Locator Strategy:

  • Using nth-child():

    div.selection div:nth-child(2) > div.circle-base
    
  • Using nth-of-type():

    div.selection div:nth-of-type(2) > div.circle-base
    

If I could correctly understand your query, there are several ways to achieve it via css pseudo-selectors. Please check the code if it helps.

/*Method 1 : using last-of-type pseudo-selector*/
[data-short-caption="itemName" i]:last-of-type .circle-base{
  background-color: #efefef;
}
/*Method 2 : using last-child pseudo-selector*/
[data-short-caption="itemName" i]:last-child .circle-base{
  background-color: #efefef;
}
/*Method 3 : using nth-of-type pseudo-selector*/
[data-short-caption="itemName" i]:nth-of-type(2) .circle-base{
  background-color: #efefef;
}
/*Method 4 : using nth-child pseudo-selector*/
[data-short-caption="itemName" i]:nth-child(2) .circle-base{
  background-color: #efefef;
}
<div class="selection" data-select-item="select-item">
    <div data-short-caption='itemName'>
      <div class=circle-base> first child </div>
    </div>
    
    <div data-short-caption='itemName'>
     <div class=circle-base> second child </div>
    </div>
</div>

Related