Okay guys. What i’m trying to do is create an unordered list (ul) with nested (ul)’s inside of it. I’m trying to modify the classes within the elements of the main (ul)’s and i have no idea how to do this. Let me give you an example. Let’s say i have this:
<ul id="mainNav">
<li><a href="#">Main Item 1</a></li>
<li><a href="#">Main Item 2</a>
<ul>
<li><a href="#">subitem1</a></li>
<li><a href="#">subitem2</a></li>
</ul>
</li>
<li><a href="#">Main Item 3</a></li>
<li><a href="#">Main Item 4</a>
<ul>
<li><a href="#">subitem3</a></li>
<li><a href="#">subitem4</a></li>
</ul>
</li>
</ul>
What i’m trying to do is find the nested (ul)’s in the “mainNav” and apply with jquery a class to them. Further more, i need to apply a class and other attributes to the parent (li)’s of the nested (ul)’s. I hope this makes sense. The output would look something like this:
<ul id="mainNav">
<li><a href="#">Main Item 1</a></li>
<li class="dropdown"><a href="#" DATA="BLAH">Main Item 2</a> <!-- STUFF GOES HERE -->
<ul class="dropdown-submenu"> <!-- and here -->
<li><a href="#">subitem1</a></li>
<li><a href="#">subitem2</a></li>
</ul>
</li>
<li><a href="#">Main Item 3</a></li>
<li class="dropdown"><a href="#" DATA="BLAH">>Main Item 4</a>
<ul class="dropdown-submenu">
<li><a href="#">subitem3</a></li>
<li><a href="#">subitem4</a></li>
</ul>
</li>
</ul>
I hope this makes sense. I’m trying to traverse the child elements and add classes to the child elements (ul)’s and then go to the parent element (li) and add classes to that and the (a) elements as well. I’m completely lost and if you guys could help, i would greatly appreciate it!!! Thanks all!!!
That’s fairly straightforward to do with a single jQuery line:
$('#mainNav ul').addClass('dropdown-submenu').parent('li').addClass('dropdown');Note that using the css selectors, we’re just finding any
ulelements of the mainNav, then adding a class, then we chain another function to find it’s parent, and add a class off dropdown.EDIT :
To add the data attribute to the a tag per the example in the question, chain in the
find('a:first').attr('data', 'BLAH')bit like so:EDIT 2 :
To address the next level of ul children, and presumably NOT have all child ul’s have the same class, you can use the following script:
Note the change in selector for the first line: this ensures we only get the
ul‘s that are direct descendants of the top-levellielements.The second line selector tells it to get all third level+
ulelements (it will get all third, fourth, etc. levelulelements).