JQuery: exclude elements from .each () selector?

I want to loop through the menu items contained in 3 nested s <ul>

, but only extract .HTML () from the second layer of nested <li>

s, like so:

<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>

      

Usually I would use .not (), for example:

$.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 the 2nd and 3rd level tags.

Does anyone know how to change this at all?

+3


source to share


1 answer


You can use the child selector [docs] :

$("#menu > ul > li > ul > li > a").each(...);

      



Or count the number of ancestors li's

, although this is likely to be less productive:

$('#menu ul a').filter(function() {
    return $(this).parentsUntil('#menu', 'li').length === 2;
}).each(...);

      

+3


source







All Articles