Im using this to toggle the visibility of an element:
$(".trigger").click(function() {
$(this).next().slideToggle();
});
<p class="triggger">Trigger</p>
<p class="target">this is the target</p>
Its working fun but I want to make it so the next element is only toggled if it has a class of target. The following isnt working:
$(this).next().hasClass("target").slideToggle();
this will do the trick:
$(this).next(".target").slideToggle();
.slideToggle()
will only be fired on next element if that has a className of target
only.
The function hasClass('target') returns a boolean..So instead change your function to the following.
$(".trigger").click(function() {
if($(this).next().hasClass('target')) { $(this).next().slideToggle(); }
});
Regards.
Jquery .next()
, support selector(.next([selector ])
).
Try This :
$(".trigger").click(function() {
$(this).next(".target").slideToggle();
});
$(this).next(".target")
- will select the very next sibling of each elements with trigger class. Keep only the ones with a class "target".
Working Example
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