Here is the HTML code snippet I am working with:
<div class="nav-collapse collapse">
<ul class="nav">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li class="nav-header">Nav header</li>
<li><a href="#">Separated link</a></li>
<li><a href="#">One more separated link</a></li>
</ul>
</li>
</ul>
</div>
In order to dynamically add classes and attributes to elements using jQuery, I need to target specific elements. For example, if the parent element of a ul
is an li
, I want to add classes to both the ul
and its parent.
Here is how I am attempting to achieve this using jQuery:
$(".nav-collapse").find("ul").first().addClass("nav");
$(".nav-collapse").find("li").hast("ul").addClass("nav");
$(".nav").find("li a").attr("data-toggle", "dropdown").append("<b class='caret'></b>");
$(".nav").find("li ul").addClass("dropdown-menu");
$(".nav").find("li ul li").addClass("dropdown-submenu");
$('.dropdown-toggle').dropdown();