Heather Heather - 1 month ago 5
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)
.addClass('in');
};


https://jsfiddle.net/n94Lwe9t/

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

Answer

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')
     $(this).closest('.children').addClass('in');
  }

})

JSFIDDLE

Comments