I want to loop through a series of menu items contained within 3 nested <ul>s but only retrieve the .HTML() from the 2nd layer of nested <li>s, eg:
<ul>
<li><a href="#">Ignore</a></li>
<li><a href="#">Ignore</a></li>
<li><a href="#">Ignore</a>
<ul>
<li><a href="#">Retrive me</a></li>
<li><a href="#">Retrive me</a></li>
<li><a href="#">Retrive me</a>
<ul>
<li><a href="#">Ignore</a></li>
<li><a href="#">Ignore</a></li>
<li><a href="#">Ignore</a></li>
</ul>
</li>
</ul>
</li>
</ul>
Normally I would use .not() eg:
$.each($("#menu ul li ul li a").not("#menu ul li ul li ul li a"), function() {
var linktext = $(this).html();
console.log(linktext);
});
But this still returns all .html() from 2nd and 3rd level a tags.
Would anyone know how to amend this at all?
You can use the child selector [docs]:
$("#menu > ul > li > ul > li > a").each(...);
Or count the number of ancestor li's although that would probably be less performant:
$('#menu ul a').filter(function() {
return $(this).parentsUntil('#menu', 'li').length === 2;
}).each(...);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With