How to apply! important of CSS via Jquery?

29

I'm trying to apply a style to my element and define its importance in this way:

$('div').css('height','50px!important');

However, it does not work, what would be the right way?

    
asked by anonymous 07.01.2014 / 13:52

4 answers

12

It is not working because Jquery does not recognize the statement! In a simple way, you can do this:

$('div').attr('style', 'width: 50px!important');

This should work, but it will override the previous styles that have been set. For this to happen, this will keep the previous styles and add new ones:

$('#elem').attr('style', function(i,s) { return s + 'width: 100px !important;' });
    
07.01.2014 / 13:52
14

The best way to apply CSS rules is to always use classes.

So it's best to define a CSS class

.minhaClasse {
    width: 50px!important
}

and add the class with:

$('#elem').addClass('minhaClasse');

Apart from this ideal way, and taking into account that jQuery is javascript might be better, in this case use the style and particularly the setProperty which has a parameter to importance .

So, you could use:

$('#elem')[0].style.setProperty('width', '50px', 'important');

or

document.getElementById('elem').style.setProperty('width', '50px', 'important');

Example

    
07.01.2014 / 14:26
7

You can use it this way:

$(".prodMenor:eq(6)").css("cssText", "margin-right: 0 !important");
  

Caution: in this case you need to set all desired properties.

See more at link (en)

If you want a function to apply !important separately, you have a here .

    
05.09.2014 / 18:07
2

You can use the jQuery .attr() function:

$('.prodMenor:eq(6)').attr('style','margin-right: 0 !important');

Example: FIDDLE

    
05.09.2014 / 17:54