m1k3y3
m1k3y3

Reputation: 2798

jquery: toggle children onclick

what js/jquery code would make below list toggle children when clicking "+" ?

<ul>  
<li id="1" parent="0"><a href="#">1</a></li>  
    <li id="2" parent="0"><a href="#"> + </a><a href="#">2</a>  
        <ul parent="2">  
            <li id="23" parent="2"><a href="#">2.1</a></li>  
            <li id="50" parent="2"><a href="#"> + </a><a href="#">2.2</a>  
                <ul parent="50">  
                    <li id="123" parent="50"><a  href="#">2.50.1</a></li>  
                </ul>  
            </li>  
        </ul>  
    </li>
</ul>

Upvotes: 1

Views: 9348

Answers (2)

John Hartsock
John Hartsock

Reputation: 86902

Something like this

$("ul a:contains('+')").click(function () {
  var $this = $(this);
  $this.siblings("ul").show();
});

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630637

You can use .toggle() or .slideToggle() with .siblings(), like this:

$("ul a:contains( + )").click(function() {
  $(this).siblings("ul").toggle();
});

You can test it out here. Note though your IDs and attributes are invalid, you may want to use data- attributes here. Also, I suggest giving those + links a class, to make the selector much more efficient, for example:

<a href="#" class=".toggle"> + </a>

Then binding like this:

$("ul a.toggle").click(function() {
  $(this).siblings("ul").toggle();
});

Upvotes: 5

Related Questions