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.
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');
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');
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