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

查看:27
本文介绍了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.

属性没有类似的过滤器伪类.解决此问题的一种简单方法是选择每一个然后排除第一个之后的内容(此技巧在此处这里):

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 表达式:

Or an XPath expression:

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

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

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