Bram Werink
Bram Werink

Reputation: 38

How to do: "select all other elements, except this one"

I have 6 cards for testimonials for our website. The cards consist of a little bit of info and a "read more" button if you want to read the whole story. The card does expand but I want it to close the other cards.

I have tried the .not element but I can't find where to put it and it doesn't seem to work

$j=jQuery.noConflict();

jQuery('.readmore').click(function(){  
  jQuery(this).parent().addClass('uitgeklapt');
  jQuery(this).parent().not(this).addClass('weg');
});
.uitgeklapt {
  width:100%;
  height:530px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="cart left">
  <img class="image" src="https://checkbuster.com/wp-content/uploads/2019/08/BA-Group-1.png">
  <p class="tekst">Lorem ipsum dolor sit amet, consetetur</p>
  <p class="readmore">Read more</p>
  <p class="sluiten">Close</p>
</div>

I expect that when one presses "Read more" It adds a class to the other divs with a "display none."

EDIT:

I have added

jQuery('.readmore').click(function(){  
  jQuery(this).parent().addClass('uitgeklapt');
  jQuery(".cart").not($(this).parent()).addClass('weg');
  });

Yet, it doesn't give the other cards the class "weg"

Upvotes: 1

Views: 101

Answers (1)

Tomalak
Tomalak

Reputation: 338148

Quite straightforward:

var $myOwnCart = $(this).closest(".cart");
$(".cart").not($myOwnCart);

https://api.jquery.com/closest/


This would also work:

$(".cart").not($(this).parent());

but I prefer .closest() over .parent(), because the former will not stop to work just because you added a level of <div> to your HTML for some reason.

Upvotes: 1

Related Questions