Home > Net >  Jquery change css class from variable
Jquery change css class from variable

Time:09-19

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 >
 <div >
  <p >Change one</p>
  <p >Change two</p>
  <p >Change three</p>
 </div>
 <div >
   <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 !

CodePudding user response:

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 . 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();
  });

CodePudding user response:

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.

  • Related