CSS从具有特定属性的元素中选择第一个子元素 [英] CSS select the first child from elements with particular attribute

查看:1452
本文介绍了CSS从具有特定属性的元素中选择第一个子元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有以下代码:

<node>
  <element bla="1"/>
  <element bla="2"/>
  <element bla="3"/>
  <element bla="3"/>
  <element bla="3"/>
  <element bla="4"/>
</node>

如何选择属性等于3的第一个子节点?我在想,也许这可以做的工作:

How would you go about selecting the first child that has attribute equal to 3? I was thinking that perhaps this could do the job:

element[bla="3"]:first-child

...但不起作用

推荐答案

:first-child 伪类只查看第一个子节点,所以如果第一个子节点不是 element [bla =3] ,则不选择任何内容。

The :first-child pseudo-class only looks at the first child node, so if the first child isn't an element[bla="3"], then nothing is selected.

没有类似的过滤器伪类属性。一个简单的方法是选择每一个,然后排除第一个后面的内容(这个招trick在这里此处):

There isn't a similar filter pseudo-class for attributes. An easy way around this is to select every one then exclude what comes after the first (this trick is explained here and here):

element[bla="3"] {
}

element[bla="3"] ~ element[bla="3"] {
    /* Reverse the above rule */
}

这当然只适用于样式;如果你想为这个元素选择除了样式之外的目的(因为你的标记看起来是任意的XML而不是HTML),你必须使用 document.querySelector()

This, of course, only works for applying styles; if you want to pick out that element for purposes other than styling (since your markup appears to be arbitrary XML rather than HTML), you'll have to use something else like document.querySelector():

var firstChildWithAttr = document.querySelector('element[bla="3"]');

或XPath表达式:

//element[@bla='3'][1]

这篇关于CSS从具有特定属性的元素中选择第一个子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆