Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery if element is next and has class?

Tags:

jquery

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();
like image 950
Evanss Avatar asked May 16 '14 13:05

Evanss


3 Answers

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.

like image 59
Jai Avatar answered Sep 18 '22 17:09

Jai


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.

like image 41
Hardeep Mehta Avatar answered Sep 21 '22 17:09

Hardeep Mehta


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

like image 33
Ishan Jain Avatar answered Sep 22 '22 17:09

Ishan Jain