I’m new here, and in Jquery …
I am using WordPress to create a website and I have a Jquery function for opening cards, these cards have a plus button, and clicking that button opens a description of the card …
So far so ok, but all the cards have the same classes (on the button, and the description) and pulling it on the page I need to use them by clicking on one of the buttons it opens all the descriptions of the other cards … can i make it open only the card description of the button i clicked?
Code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(this).ready(function(){
$(".abrir-btn").click(function(){
$(".conteudo-div").show(200);
$(".abrir-btn").hide();
$(".fechar-btn").show();
$(".listing-nucleados").css("background-color", "#FFE500");
$(".listing-nucleados").css("border-color", "#fff");
});
$(".fechar-btn").click(function(){
$(".conteudo-div").hide(200);
$(".abrir-btn").show();
$(".fechar-btn").hide();
$(".listing-nucleados").css("background-color", "#fff");
$(".listing-nucleados").css("border-color", "#EBEBEB");
});
});
</script>
2
Answers
Assuming, the buttons as well as the
.listing-lucleados
are both wrapped inside a parent element (let’s call it.my-parent
here). You can do the following:Basically, what this does is going up the DOM tree to the parent element wrapping the show/hide buttons, as well as the list to show/hide. Then, from the parent element, find its descendants (I’m not saying direct children, because I do not know that much about your HTML structure) and apply the operation only to elements of this class inside the parent element.
In the function performed after clicking the button find a common ancestor of both elements – the button and the description – using
closest()
.Having an ancestor, find in it elements with the class
.abrir-btn
,.fechar-btn
or.conteudo-div
.Example HTML: