views:

4649

answers:

3

I have some HTML that looks like this:

<ul class="faq">
    <li class="open">
        <a class="question" href="">This is my question?</a>
        <p>Of course you can, it will be awesome. </p>
    </li>
</ul>

Using CSS I'm setting the 'p' tag to display:none;. I want to use jQuery to display or hide the 'p' tag when the anchor is clicked, but I'm having some troubles with the sibling selector.

Just trying to get the selector working, I tried:

$("a.question").click(function () {
    $(this + " ~ p").css("background-color", "red");
});

to test it out. Seemingly, the sibling selector can't really be used like that, and as I'm completely new to jQuery I don't know the appropriate means to make that happen.

Thanks in advance!

+4  A: 
$(this).next("p").css("...")

the "p" above is optional, if you just want the next non-whitespace node in the DOM.

Ben Scheirman
+13  A: 

Try using:

$(this).siblings('p').css()
swilliams
Sweet, this is perfect (and much faster than a rather fruitless Google search). Thanks!
ironkeith
lazyweb is great isn't it? :) Oh and keep in mind that it will do that to _every_ 'p' tag in your <li> if you add more.
swilliams
then you should probably be using *my* answer below :) but I'm not bitter...
Ben Scheirman
+3  A: 

I want to use jQuery to display or hide the 'p' tag when the anchor is clicked

Since you mentioned that you'd like to toggle the 'p' tag when the anchor is clicked, I'd do:

  $("a.question").click(function (event) {
      $(this).siblings('p').show(); //toggle the p tags that are siblings to the clicked element
      event.preventDefault(); //stop the browser from following the link
  });
Gabe Hollombe
Ah, I had been wondering what the jQuery version of consuming a click event was. Thanks!
swilliams
Hey thanks, that saved me having to think further! I ended up going with slideToggle() instead of show() though, mostly because I want people to think I'm cool. ;)
ironkeith
Glad I could help! =-)
Gabe Hollombe