如何选择具有给定类名的第一个、第二个或第三个元素? [英] How to select the first, second, or third element with a given class name?

查看:38
本文介绍了如何选择具有给定类名的第一个、第二个或第三个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在元素列表中选择某个元素?我有以下内容:

<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.

这篇关于如何选择具有给定类名的第一个、第二个或第三个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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