Add Class to Parent LI if it has Child UL Inside

Posted on December 6, 2015 by Dan Doicaru in jQuery/JavaScript Category with Easy Difficulty

In this simple tutorial you will learn how to add class to parent li (list item) if it has child ul (unordered list) inside, using jQuery, useful when you want to target only menu items with ul inside.

To achieve this thing you won't need any fancy scripts to check if the <li> has <ul> inside or any other checks. You will need to use only one row of jQuery that targets any li followed by any ul inside it.

Video Tutorial

Add Class to Parent LI if it has Child UL Inside

Add Class to Parent LI if it has Child UL Inside

To add class to parent li with another child ul inside it, you need just to target the ul and use the parent() function to go up one level in the DOM tree to select the li. If the ul will not be found inside the list item, the jQuery code will not be executed.

// Add Class to LI with Child UL (Level 1)
$('.menuContainer li ul').parent().addClass('hasChild');

Add Class to Child LI that has Sub Child UL

To add another class to all list items from level 2 lists that has ul inside, you just need to target two list items and an ul. This will add a second class only to level 2 list items, useful when you want to give different actions to class based list.

// Add Another Class to Child LI with Sub Child UL (Level 2)
$('.menuContainer li li ul').parent().addClass('hasSubChild');

List Items with Class for Inner Lists

If you want to add a third class to level 3 menu you can copy the same line for level 2, but you only need to add one more list item in the jQuery selector. You can check the demo below or download the files to see the entire code there

Live Demo

Download Files

Rate & Share
1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 5.00 out of 5)
Related Articles
Hint: Wrap your code syntax (html, css or others) between <pre> and </pre> tags. All comments are moderated.

7 + 4 =

Subscribe by E-mail

HTML-TUTS is created and maintained by Dan Doicaru.
This website is a rebrand to Extreme Design Studio (, built under WordPress platform.