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

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

问题描述

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

 < div class =myclass> my text1& div> 
<! - 其他一些代码如下 - >
< div>
< p> stuff< / p>
< / div>
< div>
< p>个更多内容< / p>
< / div>
< p>
< span> Hello World< / span>
< / p>
< div class =myclass> my text2< / div>
<! - 其他一些代码如下 - >
< div>
< p> stuff< / p>
< / div>
< p>
< span> Hello World< / span>
< / p>
< input type =/>
< div class =myclass> my text3< / div>
<! - 其他一些代码如下 - >
< div>
< p> stuff< / p>
< / div>
< footer>结束< / footer>

我有CSS类 div.myclass {doing things} 适用于所有,显然,但我也想要能够选择类 .myclass 的第一,第二或第三个div像这样,

  div.myclass:first {color:#000;} 
div.myclass:second {color:#FFF;}
div.myclass:third {color:#006;}

几乎像jQuery索引选择 .eq(index),这是我目前使用的,但我需要一个无脚本的替代。



具体来说,我正在寻找伪选择器,而不是像添加另一个类或使用ID来使事情工作。

解决方案

你可能最终意识到这个问题和今天发布之间,但选择器的本质使得不可能通过分层不相关的HTML元素。



或者,简单地说,因为您在注释中说:


没有统一的父容器


...它是不可能的选择器单独,

使用jQuery .eq() c $ c>解决方案。


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天全站免登陆