HTML:
<ul class="menu">
<li><a href="">Text</a>
<ul>
<li><a href="">Text</a>
<li><a href="#">Text</a>
<li><a href="#">Text</a>
</ul>
</li>
<li><a href="">Text</a></li>
<li><a href="">Text</a></li>
<li><a href="">Text</a></li>
<li><a href="#">Text</a>
<ul>
<li><a href="#">Text</a>
<li><a href="#">Text</a>
<li><a href="#">Text</a>
</ul>
</li>
<li><a href="#">Text</a></li>
</ul>
JS:
$(".menu li a").click(function() {
$(this).parent().find("ul").toggle();
return false;
});
How to make this js work only when <li>
has <ul>
inside it?
Without adding extra classes.
It should not work when there is no child <ul>
inside current <li>
.
Example of this available on jsfiddle
Its better if you give link to your working example.
HTML:
<ul class="menu">
<li><a href="http://google.">Text</a>
<ul>
<li><a href="http://google.">Text</a>
<li><a href="#">Text</a>
<li><a href="#">Text</a>
</ul>
</li>
<li><a href="http://google.">Text</a></li>
<li><a href="http://google.">Text</a></li>
<li><a href="http://google.">Text</a></li>
<li><a href="#">Text</a>
<ul>
<li><a href="#">Text</a>
<li><a href="#">Text</a>
<li><a href="#">Text</a>
</ul>
</li>
<li><a href="#">Text</a></li>
</ul>
JS:
$(".menu li a").click(function() {
$(this).parent().find("ul").toggle();
return false;
});
How to make this js work only when <li>
has <ul>
inside it?
Without adding extra classes.
It should not work when there is no child <ul>
inside current <li>
.
Example of this available on jsfiddle
Its better if you give link to your working example.
Share Improve this question edited Nov 13, 2010 at 16:40 James asked Nov 13, 2010 at 16:34 JamesJames 43.7k54 gold badges137 silver badges163 bronze badges 2-
What do you want it to do when there is a child
ul
? – David Thomas Commented Nov 13, 2010 at 16:39 - @David Thomas, if there is a child <ul> inside current <li>, when we click on first link inside current list item, <ul> should bee visible (toggle effect). Otherwise we don't do anything (no js for this list item). – James Commented Nov 13, 2010 at 16:43
3 Answers
Reset to default 2Try restricting the parent to bring back the first li
, right now it is finding the ul
of an li
as the top level container then has within it several other ul
so the logic is working as written.
$(".menu li a").click(function() {
return !($(this).parents("li:first").find("ul").toggle().length)
});
To perform an action if there's a child ul
of the currently-hovered li
:
$('li').hover(
function(){
if ($(this).has('ul')) {
// do stuff
}
});
I was going to add that you could also just use the :has
selector with a parent > child
selector (demo):
$('.menu li:has(ul) > a').click(function() {
$(this).parent().find('ul').toggle();
return false;
});