如何从CSS选择器中选择第n个项目

问题描述

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

此选择器在DOM中标识了两个项目,我需要选择第二个项目,是否有像xpath中那样选择第二个项目的方法

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>

解决方法

按照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>

要仅标识第二项,可以使用以下基于Locator Strategy中的任何一个:

  • 使用nth-child()

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

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

如果我能正确理解您的查询,有几种方法可以通过CSS伪选择器来实现。请检查代码是否有帮助。

/*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>