For my site, I code a button allowing to change the css of a class present in a div card. My button is located in the card-footer. Having several cards, I can’t / don’t think to retrieve the element with an id (as there will be X times the same ID)
In order to circumvent this system, I therefore use a parentElement which goes up to the div card
<div class="card">
<div class="card-body">
<p class="change">Change one</p>
<p class="change">Change two</p>
<p class="change">Change three</p>
</div>
<div class="card-footer">
<i id="updateData">change</i>
</div>
</div>
jQuery($ => {
$('#updateData').click(e => {
var element = e.target.parentElement.parentElement;
$('.change').css('display','none');
});
});
I would like to indicate that only the class "changes" present in my element variable and not all the classes in the page.
I don’t know how to add a variable to my ".css" command, do you know how ?
Thanks in advance !
2
Answers
First of all since you will have multiple elements with same id that means that you should not use ID and use class instead. Id is meant to be unique. So yours
id="updateData"
should becomeclass="updateData"
. Now you can grab all of those buttons and assign event to all of them instead of just first like you were by using id selector.Next in order to be able to use clicked element in jQuery way convert from arrow function to regular anonymous function since arrow function overrides
this
keyword. And now you can use jQuery to hide likeIf you want more precise selection to hide only
.change
elements useNot bad, but more efficient, when you have multiple click targets, is delegation:
Also .hide() is convenient, but rather then "change the css of a class" add a class "hidden" or something! In best case the class further describes what the element is. CSS is just on top.