views:

66

answers:

5

How do I select sibling node of the current node? Here is the snippet:

<div id="main">
    <a class="test" href="test.html">Hello</a>
    <div>Some text</div>
</div>

//script
$(".test").click(function() { $("this:parent > div").toggle(); });
or
$(".test").click(function() { $("this ~ div").toggle(); });

None of these works. I know I can access current object using $(this) but in this case I don't know how.

+1  A: 

Be sure to not put this in quotes.

$(".test").click(function() { 
    $(this).next().toggle(); 
});

jQuery has lots of great functions for traversing.

Docs: http://api.jquery.com/category/traversing/

patrick dw
A: 

Use .siblings()

http://api.jquery.com/siblings/

Ken Redler
+3  A: 

Here are a few options:

$(".test").click(function() { 
    $(this).next('div').toggle(); 
});

$(".test").click(function() { 
    $(this).siblings('div').toggle(); 
});

$(".test").click(function() { 
    $(this).closest('div#main').find('div').toggle(); 
});

Just depends on what else is in your HTML markup for which one you want to choose.

munch
A: 

Are you trying to toggle the #main div? If so, wouldn't .parent() give you the parent div?

http://api.jquery.com/parent/

I'd think that you'd have to use something like:

$(".test").click(function() { $(this).parent("div").toggle(); });
gurun8
His question seems pretty clear that he wants the sibling, not the parent.
patrick dw
A: 

You can re-scope your selector:

$(".test").click(function() { $("~ div", this).toggle(); });
patridge