Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery: Exclude elements from .each() selector?

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?

like image 514
MeltingDog Avatar asked Dec 05 '25 08:12

MeltingDog


1 Answers

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(...);
like image 157
Felix Kling Avatar answered Dec 07 '25 20:12

Felix Kling