jQuery check childNode class

I'm trying to figure out how to check the class of a childNode. I currently have a list like this:

<li>
    <a href="#">Link</a>
    <ul class="children">
        <li class="current"></li>
        <li></li>
        <li></li>
    </ul>
</li>

Previously, an additional 'active' class was being applied to a ul which contained a li.current, and I had this jQuery script which was doing the job of marking the parent li as active as well as the sibling a:

jQuery("ul.active").siblings('a').addClass('current').parent().addClass('current');

but the 'active' class is not longer being applied, so I need to check the children of any ul.children to see if any are li.current. I'm just not sure how to go about it ...

13.10.2009 23:26:43
3 ОТВЕТА

use the hasClass() command

if ($("ul.children li").hasClass('current')) {
    // at least one of the <li> elements of the ul has the current CSS class
}

or another way to check if at least on <li> has the CSS class current is to use length

if ($("ul.children li").length > 0) {
    // at least one of the <li> elements of the ul has the current CSS class
}

then to add the class to the sibling <a> and to the <li> further up

var listItems = $("ul.children li");

if (listItems.length > 0) {
   listItems.parents('li').children('a').andSelf().addClass('current');
}
1
14.10.2009 06:02:45

working code:

jQuery("ul.children li.current").parent().siblings('a').addClass('current').parent().addClass('current');
1
14.10.2009 00:15:56
$('a, ul.children:has[li.current]', $('li:has[li.current]').addClass('current')).addClass('current')
0
14.10.2009 06:18:34