Heather
Heather

Reputation: 305

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?

Upvotes: 0

Views: 219

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281804

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

Upvotes: 1

Related Questions