Reputation: 39364
I am creating a tree in HTML with child nodes ...
I need to show/hide an UL when the A tag on the same LI is clicked.
In the following example, the UL containing 3.1 and 3.2 should show/hide when the A tag with 3 is clicked.
$("a").on("click", function() {
$("ul").toggle()
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li>
<a href="#">3</a>
<ul>
<li><a href="#">3.1</a></li>
<li><a href="#">3.2</a></li>
</ul>
</ul>
Note: At the moment I am using "a" on click but it should be only the A tags that have a UL on the same LI.
Upvotes: 1
Views: 1003
Reputation: 24965
//bind only on the 'a's that have a sibling 'ul'
$("a").filter(function(){
return ( $(this).siblings('ul').length > 0 );
}).on("click", function(e) {
e.preventDefault();
// hide sibling ul element (if it exists)
$(this).siblings("ul").toggle();
});
Upvotes: 3
Reputation: 67207
Try to use .next()
at this context to achieve what you want,
$("a").on("click", function(e) {
e.preventDefault();
$(this).next("ul").toggle();
});
Upvotes: 0