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.
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.
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.
Try using:
$(this).siblings('p').css()
$(this).next("p").css("...")
the "p" above is optional, if you just want the next non-whitespace node in the DOM.
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With