In this example I have multiple a
tags. Under the Structure
where you can see my unordered list
, that list was generated by a CMS I am using. But this ul
needs to a dropdown menu of the previous a
, which in this case is Structure
. I am trying to add some classes and attributes to the structure
, but with the code I am using, it gets all a
tags elements. But I only need the element before ul
$('.custom-dropdown').each(function() { if($(this).children('ul').length) { $(this).addClass('dropdown'); $(this).children('a').addClass('dropdown-toggle'); // the problem is here. I have tried closest(), .prev() but I couldn't use it properly to make it work $(this).children('a').attr({'role':'button','data-toggle':'dropdown','id':'navbarDropdown2'}); } });
<div class="dropdown-menu custom-dropdown" aria-labelledby="navbarDropdown"> <a href="" class="nav-link">About Us</a> <a href="" class="nav-link">Structure</a> <ul> <li class="first nav-item"> <a href="" class="nav-link">Organizational Chart</a> </li> <li class="last nav-item"> <a href="" class="nav-link">Commissioner</a> </li> </ul> <a href="" class="nav-link">Mission</a> <a href="" class="nav-link">Strategies</a> </div>
Given the structure, to find all the <a>
tags with a corresponding ul
as the next sibling, you can use:
$(this).find('ul>li>a').closest("ul").prev("a")
which will find, given this==.custom-dropdown
, any ul
(at any level) that has an li
and a
as direct descendants, then using .closest
to go back to that ul
with .prev
to get the corresponding a
that matches.
Using .prev(selector)
will select the previous only if it matches the selector, it's the same as .prev().filter(selector)
- it's not the same as .prevAll().first()
(or is that.last, either way).
Example snippet with added.hide just to demo it working - this would normally be handled by adding the drop down classes/attributes.
$(".custom-dropdown").find('ul>li>a').closest("ul").hide().prev("a").addClass("red");
.red { color: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="dropdown-menu custom-dropdown" aria-labelledby="navbarDropdown"> <a href="" class="nav-link">About Us</a> <a href="" class="nav-link">Structure</a> <ul> <li class="first nav-item"> <a href="" class="nav-link">Organizational Chart</a> </li> <li class="last nav-item"> <a href="" class="nav-link">Commissioner</a> </li> </ul> <a href="" class="nav-link">Mission</a> <a href="" class="nav-link">Strategies</a> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.