Jquery by selecting the sibling node of the current node

How to select the sibling node of the current node? Here's a 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 the current object using $ (this), but in this case, I don't know how.

+2


a source to share


5 answers


Here are some 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(); 
});

      



It just depends on what else is in your HTML markup that you want to opt for.

+5


a source


Be sure not this

to use quotation marks.

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

      



jQuery has a lot of great features to walk through.

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

+2


a source


Use .siblings()

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

0


a source


Are you trying to switch the #main div? If so, can you .parent()

provide a parent div?

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

I would think you would need to use something like:

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

      

0


a source


You can reuse your selector:

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

      

0


a source







All Articles