MeltingDog
MeltingDog

Reputation: 15404

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?

Upvotes: 3

Views: 331

Answers (1)

Felix Kling
Felix Kling

Reputation: 816334

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(...);

Upvotes: 3

Related Questions