Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using "this" with jQuery Selectors

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.

like image 254
ironkeith Avatar asked Oct 29 '08 20:10

ironkeith


People also ask

How do you get the children of the $( this selector?

Answer: Use the jQuery find() Method You can use the find() method to get the children of the $(this) selector using jQuery. The jQuery code in the following example will simply select the child <img> element and apply some CSS style on it on click of the parent <div> element.

Can you use a variable in a jQuery selector?

Projects In JavaScript & JQueryYes, it is possible to pass a variable into a jQuery attribute-contains selector. The [attribute*=value] selector is used to select each element with a specific attribute and a value containing a string.


3 Answers

Try using:

$(this).siblings('p').css()
like image 77
swilliams Avatar answered Oct 09 '22 10:10

swilliams


$(this).next("p").css("...")

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

like image 41
Ben Scheirman Avatar answered Oct 09 '22 10:10

Ben Scheirman


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
  });      
like image 7
Gabe Hollombe Avatar answered Oct 09 '22 09:10

Gabe Hollombe