[英]Add class to parents that have children using jquery
How would I go about adding a class only to the li
parent that has children? 我将如何只向有孩子的
li
父母添加课程?
<ul>
<li><a href="#">parent</a></li>
<li><a href="#">parent</a>
<ul>
<li>child</li>
<li>child</li>
</ul>
</ul>
$('li > *').parent().addClass(...);
or 要么
$('li').has('*').addClass(...);
The first version may be marginally faster if you do: 如果您这样做,第一个版本可能会稍快一些:
$('li > :first-child').parent().addClass(...);
...hard to say though without testing. ...很难说,尽管没有测试。
All of these use fully valid CSS selectors. 所有这些都使用完全有效的CSS选择器。
$('li:has(ul)').addClass('test-class');
I love how simple jQuery makes some things. 我喜欢jQuery使某些事情变得如此简单。
Here is jsfiddle of the above code: http://jsfiddle.net/p9M73/ 这是上述代码的jsfiddle: http : //jsfiddle.net/p9M73/
Here is the documentation for :has()
: http://api.jquery.com/has-selector/ 这是
:has()
的文档: http : //api.jquery.com/has-selector/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.