menu link selector in JQuery
I have this html menu:
<div id="menu">
<ul>
<li>
<a href="1.html"> 1 </a>
</li>
<li>
<a href="2.html"> 2 </a>
</li>
<li class="submenu">
<a href="#"> 3 list </a>
<ol>
<li>
<a href="31.html"> 31 </a>
</li>
<li>
<a href="32.html"> 32 </a>
</li>
<li>
<a href="33.html"> 33 </a>
</li>
</ol>
</li>
<li class="submenu">
<a href="#"> 4 list </a>
<ol>
<li>
<a href="41.html"> 41 </a>
</li>
<li>
<a href="42.html"> 42 </a>
</li>
</ol>
</li>
<li>
<a href="5.html"> 5 </a>
</li>
</ul>
</div>
I'm using JQuery and I wanted to get the link elements (a) that are not part of the submenu (1,2 and 5), so i tried:
$('#menu ul li a').each(function(){
//do something with the link element
});
But i realized that this selector takes all the link elements(1,2,31,32,33,41,42 and 5).
I checked the JQuery manual and i could not find any way to get the link elements that I want in only one step, so I finally did this:
$('#menu ul li a').each(function(){
if($(this).parent().parent().is('ul')){
//do something with the link element
}
});
That just takes all the link elements and in the conditional filters the ones that have an ul grandfather (1,2 and 5).
I would like to know if the开发者_如何学编程re is a better and more clean way to get the not submenu link elements.
Thanks!
Try this
$('#menu ul li a').not("li.submenu").each(function(){ });
Actually, that may return the inside li(s) still.
So maybe another not?
$('#menu ul li a').not(".submenu").not(".submenu *").each(function(){ });
Hopefully I'm not mistakenly on understanding your question..
You want to get first level li
elements which don't have sub list? Then it means li
element 1, 2 & 5? If so, try this:
$('#menu ul > li:not(:has(li))').each(...);
It only check for first level element after #menu
by using >
sign. Then filter again for each li
that doesn't has li
inside.
Hope this helps..
精彩评论