Heather Heather - 2 years ago 76
jQuery Question

JQuery: All Submenu's expand if a child in one has class

I have a little piece of code that expands a submenu by adding the class "in" to the parent if a child element contains the class "current_page_item". The problem is, if any submenus have a child of that class they all expand.

if ( $('.children li').hasClass('current_page_item') ) {
$('.children', this)


I can't target ID's or anything else specific. How would I target the particular parent that has that child class?

Answer Source

Loop over the child elements li of children class and then use closest() to find the appropriate parent

$('.children li').each(function(){

    if($(this).hasClass('current_page_item')) {
    console.log($(this).closest('.has-children').find('.list-group-item .glyphicon'));
    $(this).closest('.has-children').find('.list-group-item .glyphicon').toggleClass('glyphicon-chevron-right').addClass('glyphicon-chevron-down')



Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download