I wants to achieve the id(i.e – menu-right-2
) of outer ul in jquery when I found two.html link in browser. with following code.
var fullpath = window.location.pathname;
var filename = fullpath.replace(/^.*[\/]/, '');
var currentLink = $('a[href="' + filename + '"]');
var menuid = currentLink.parentsUntil('.menu-bar-right', 'ul').attr('id');
console.log(menuid);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div class="menu-bar-right">
<ul id="menu-right-2">
<li class="nav-link">
<a href="#">
<span class="text nav-text">Yes</span>
</a>
<ul>
<li class="nav-link">
<a href="two.html">
<span class="text nav-text">Two</span>
</a>
</li>
</ul>
</li>
<li>Hello</li>
</ul>
</div>
2
Answers
parentUntil stops before the div you want
You mean this – closest STILL works well here
Multiple ULs in one div
You need to use the
.closest()
method instead of.parentsUntil()
to find the outer element.