How to select the first, second, or third element with a given class name?(如何选择具有给定类名的第一个、第二个或第三个元素?)
问题描述
如何在元素列表中选择某个元素?我有以下内容:
<div class="myclass">my text1</div><!-- 后面还有一些其他代码--><p>东西</p></div><p>更多内容</p></div><p><span>你好世界</span></p><div class="myclass">我的文本2</div><!-- 后面还有一些其他代码--><p>东西</p></div><p><span>你好世界</span></p><输入类型=""/><div class="myclass">我的文本3</div><!-- 后面还有一些其他代码--><p>东西</p></div><footer>结尾</footer>显然,我有适用于所有的 CSS 类 div.myclass {doing things}
,但我也希望能够选择类 .myclass
像这样,不管它们在标记中的什么位置:
div.myclass:first {color:#000;}div.myclass:second {颜色:#FFF;}div.myclass:第三{颜色:#006;}
几乎像 jQuery 索引选择 .eq(index)
,这是我目前正在使用的,但我需要一个无脚本的替代方案.
具体来说,我正在寻找伪选择器,而不是像添加另一个类或使用 ID 来使事情正常工作之类的东西.
解决方案 您可能在发布这个问题和今天之间终于意识到了这一点,但是选择器的本质使得它无法在层次不相关的 HTML 元素中导航.
或者,简单地说,因为你在评论中说过
<块引用>没有统一的父容器
...如果不以其他答案所示的某种方式修改标记,单独使用选择器是不可能的.
您有使用 jQuery .eq()
解决方案.
How can I select a certain element in a list of elements? I have the following:
<div class="myclass">my text1</div>
<!-- some other code follows -->
<div>
<p>stuff</p>
</div>
<div>
<p>more stuff</p>
</div>
<p>
<span>Hello World</span>
</p>
<div class="myclass">my text2</div>
<!-- some other code follows -->
<div>
<p>stuff</p>
</div>
<p>
<span>Hello World</span>
</p>
<input type=""/>
<div class="myclass">my text3</div>
<!-- some other code follows -->
<div>
<p>stuff</p>
</div>
<footer>The end</footer>
I have the CSS class div.myclass {doing things}
that applies to all, obviously, but I also wanted to be able to select the first, second, or third div of class .myclass
like this, regardless of where they are in the markup:
div.myclass:first {color:#000;}
div.myclass:second {color:#FFF;}
div.myclass:third {color:#006;}
Almost like the jQuery index selection .eq( index )
, which is what I am using currently, but I need a no-script alternative.
To be specific, I am looking for pseudo selectors, not things like adding another class or using IDs to make things work.
解决方案 You probably finally realized this between posting this question and today, but the very nature of selectors makes it impossible to navigate through hierarchically unrelated HTML elements.
Or, to put it simply, since you said in your comment that
there are no uniform parent containers
... it's just not possible with selectors alone, without modifying the markup in some way as shown by the other answers.
You have to use the jQuery .eq()
solution.
这篇关于如何选择具有给定类名的第一个、第二个或第三个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何选择具有给定类名的第一个、第二个或第三


- Flexslider 箭头未正确显示 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 400或500级别的HTTP响应 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06