I’m working with an unordered list of links that has two levels:
<ul class="level-1">
<li class="item-a"><a href="#">A</a></li>
<li class="item-b"><a href="#">B</a>
<ul class="level-2">
<li class="item-1"><a href="#">1</a></li>
<li class="item-2"><a href="#">2</a></li>
<li class="item-3"><a href="#">3</a></li>
</ul>
</li>
<li class="item-c"><a href="#">C</a></li>
</ul>
I click one of the .level-2 links, and want to select the higher level link from the list that contains the clicked link. (For example, I click either 1, 2, or 3 – and I want to select B.)
If my clicked link is selected as $(this).find('a') — how can I select the higher level link?
Would appreciate your advice!
One way would be to go up to the closest
<ul>, then up again to the closest<li>, and then back down to the<a>:This approach is fairly flexible and not overly dependent on your DOM structure, you’d be able to add things before or after the
<a>you want without breaking your code (unless of course you started adding<li>s or<ul>s).There are certainly other ways to do this but the above is pretty simple and straight forward and that should be your second concern (your first being that it works).
Referenences:
closestfind:first