[英]Jquery: How to select :first-child with :not(class)
I would like to select first occurrence of li
from an ul
which is not having particular class. 我想从没有特定类别的
ul
选择li
首次出现。
Check below snippet for example, Here I wanted add class red
to first li
which is not having class myClass
. 例如,在下面的代码段中进行检查,在这里我想将
red
类添加到没有类myClass
第一个li
中。 Here am expecting <li>Two</li>
should add class red
. 在这里,期望
<li>Two</li>
应该添加class red
。
$(document).ready(function() { $('ul li:not(.myClass):first-child').addClass('red'); });
.red { color: red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li class="myClass">One</li> <li>Two</li> <li>Three</li> <li>Four</li> <li>Five</li> </ul>
Update: In same way I wanted to select second-child as well. 更新:同样,我也想选择第二个孩子。 Is it possible?
可能吗?
Thanks in Advance. 提前致谢。
Use :first
instead of :first-child
selector 使用
:first
而不是:first-child
选择器
$(document).ready(function() { $('ul li:not(.myClass):first').addClass('red'); });
.red { color: red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li class="myClass">One</li> <li>Two</li> <li>Three</li> <li>Four</li> <li>Five</li> </ul>
You can target element based on index using .eq(index)
您可以使用
.eq(index)
根据索引来定位元素
$('ul li:not(.myClass):eq(1)').addClass('red');
You just need to use :first
instead of using :first-child
. 您只需要使用
:first
而不是:first-child
。 So your selector should like 'ul li:not(.myClass):first'
因此,您的选择器应该喜欢
'ul li:not(.myClass):first'
$(document).ready(function() {
$('ul li:not(.myClass):first').addClass('red');
});
Eidted Eidted
After your comment, I would like to recommend jquery eq() function. 发表您的评论后,我想推荐jeq eq()函数。 By using eq() you can select any
li
by passing nth number of li
. 通过使用eq(),您可以通过传递第n个
li
来选择任何li
。
$('ul li:not(.myClass):eq(1)').addClass('red');
For eq()
function first position of li
is 0
对于
eq()
函数, li
第一个位置为0
try 尝试
$(document).ready(function() {
$('ul li:first-child').addClass('red');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.