简体   繁体   English

将nth-child与类匹配的元素

[英]Matching element using nth-child with class

I want to use :nth-child to select the second span using its class 我想使用:nth-child使用其类选择第二个跨度

<div id="myDiv">
     <span class="mySpans">Stuff</span>
     <span class="mySpans">Stuff</span>
     <span class="mySpans">Stuff</span>
</div>

I am trying the following with no luck 我没有运气尝试以下

'div#myId > span:nth-child(2 of span.mySpans)';

I am specifically looking to match the element using the nth occurance a class. 我专门在寻找使用第n个匹配项匹配元素的类。

Currently, only Safari supports the selector-list argument of :nth-child() introduced in selectors-4. 当前,仅Safari支持在selectors-4中引入的:nth-child()的选择器列表参数。

There is no other way to do this in CSS besides adapting the overriding technique from here , but with an additional selector for the 3rd .mySpans onward: 除了从这里改写覆盖技术之外,在CSS中没有其他方法可以执行此操作,但是从第3个.mySpans开始有一个附加选择器:

div#myId > span.mySpans, div#myId > span.mySpans ~ span.mySpans ~ span.mySpans {
  /* ... */
}

div#myId > span.mySpans ~ span.mySpans {
  /* Remove from previous rule */
}

If this is in JavaScript or some other API that returns a set of elements as the string-like notation in your question suggests, you can just index off of it since your parent element has an ID and therefore you're only concerned with one set of elements (assuming the parent ID is actually unique, of course): 如果这是在JavaScript或某些API中返回的一组元素(如您的问题中类似字符串的符号所示),则可以对其进行索引,因为您的父元素具有一个ID,因此您只关心一组的元素(当然,假设父ID实际上是唯一的):

document.querySelectorAll('div#myId > span.mySpans')[1]

See also: Can I combine :nth-child() or :nth-of-type() with an arbitrary selector? 另请参见: 我可以将:nth-​​child()或:nth-​​of-type()与任意选择器结合使用吗?

Obviously the much-requested :nth-of-class doesn't exist yet. 显然,要求非常高的:nth-of-class还不存在。

But if you are happy to use a javascript translation* of this hypothetical CSS: 但是,如果你乐于使用这种假设的 CSS的一个JavaScript翻译*:

#myDiv .mySpans:nth-of-class(2) {
color: red;
}

there are two possible translations: 有两种可能的翻译:

document.getElementById('myDiv').getElementsByClassName('mySpans')[1].style.color = 'red';

document.querySelectorAll('#myDiv .mySpans')[1].style.color = 'red';

NB It's not a real translation, of course - it simply locates the element in the Document Object Model (DOM) and then applies style="color: red;" 注意 当然,这不是真正的翻译-它只是在文档对象模型(DOM)中定位元素,然后应用style="color: red;" to that element. 那个元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM