Set css attribute in onclick event

I have a problem with the set fontStyle attribute for a single element (by id ) in a popover. I get an onClick event, set the style ( bold font style) to all elements of the class, and then try to put another style ( normal ) in one (clicked) element. My code is:

 $(document).on('click', '.listElement', function () { $('.listElement').css('font-weight', 'bold'); alert(this.id); $(this).css('font-weight', 'normal'); }); 

There is a demonstration

Setting the bold style for all elements of the class works and the dialog displays the id correctly, therefore it is the correct element (in this ), but the .css() method .css() not work. I tried to put the style using id like:

 $('#A').css('font-weight', 'normal'); 

and there is no error in the console, but it does not work. Is there any other way to set fontStyle to a single unique element?

+5
source share
1 answer

Instead of removing CSS styles, why not just add it to the clicked object?

Get the identifier of the object with a click and use it ...

 $(document).on('click', '.listElement', function () { var clickEl = this.id; //ID of clicked object $('.listElement').not('#' + clickEl).css('font-weight', 'bold'); //bolds everything which is NOT the clicked item. alert(this.id); }); 

or

 $(document).on('click', '.listElement', function () { $('.listElement').not('#' + this.id).css('font-weight', 'bold'); //bolds everything which is NOT the clicked item. alert(this.id); }); 

Updated script


if there is a specific reason, you need to remove the style, not apply it ...

 $(document).on('click', '.listElement', function () { $('.listElement').css('font-weight', 'bold'); alert(this.id); $('.listElement#' + this.id).css('font-weight', 'normal'); }); 

Script for

+2
source

Source: https://habr.com/ru/post/1266793/


All Articles