skip to Main Content

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


  1. 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 become class="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.

     $('.updateData').click(e=> {});
    

    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 like

     $('.updateData').click(function() {
        element = $(this).parent().parent();
        element.hide();
      });
    

    If you want more precise selection to hide only .change elements use

      $('.updateData').click(function() {
        element = $(this).parent().parent();
        element.find(".change").hide();
      });
    
    Login or Signup to reply.
  2. Not bad, but more efficient, when you have multiple click targets, is delegation:

    $(document).on("click", ".updateData", function() { ... });
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search