JoaMika
JoaMika

Reputation: 1827

Target adjacent element in Jquery

I am using the code below to change the plus sign to minus and vice versa. This works fine if there is only one element on the page.

I have a page with multiple .handler classes and i am looking to target the #plus id next to each handler. Any ideas?

jQuery(".handler").click(function(){
   jQuery("#plus").html(function(_, html) {
        return jQuery.trim(html) == '+' ? '-' : '+';
    });
});

HTML

<div class="term_container">
<div class="handler"><span id="plus"> + </span><?php echo $term->name; ?></div>
<div>
<ul class="list">
<?php

$rp = new WP_Query( $args );
if ($rp->have_posts())
while ( $rp->have_posts() ) { 
$rp->the_post(); 

$name       = get_field('fl_profile_name');
$location   = get_post_meta(get_the_id(), 'fl_country', true);

?>
<li data-location="<?php echo $location; ?>"><a href="<?php the_permalink();?>"><?php echo $name; ?></a></li>

<?php 
}
?>
</ul>
</div>
</div>

Upvotes: 0

Views: 172

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388436

First change the ID to class since you have multiple elements with the same properties

<div class="handler"><span class="plus"> + </span><?php echo $term->name; ?></div>

then use a descendant selector to find the plus element which is within the clicked handler

jQuery(".handler").click(function () {
    var $plus = jQuery(this).find(".plus").html(function (_, html) {
        return jQuery.trim(html) == '+' ? '-' : '+';
    });
    $('.plus').not($plus).html('+')
});

Upvotes: 2

Related Questions