0

In my project element style is added through jquery from somewhere:

May be like this:

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

But now, I want to use my own like this:

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

But isn't working (may be due to file order), what can I do a force removeAttr('style') for this?

Navin Rauniyar
  • 10,127
  • 14
  • 45
  • 68

2 Answers2

0

The best thing to do would be to update or remove the other code entirely.

Failing that, you have to ensure your code runs after the other code. So you need to put the files in order, or you need to hook up your code to run in response to an event that you know occurs after the other code runs. You can't lock the style attribute, and you're already using !important so you can't create a style rule that will override it.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • and to make file order, I've placed the code in index.php at before closing of body which should be last in order. – Navin Rauniyar Oct 16 '14 at 07:43
  • @NavinRauniyar: Then perhaps the other code is running in response to jQuery's `ready` (`ready` happens later than inline code just before `

    `) or even a later event like `load`.

    – T.J. Crowder Oct 16 '14 at 07:43
  • @NavinRauniyar: Look, I've told you above what you need to do. I'm sorry you're having trouble doing it, but I can't reach out and find the offending code for you. If `ready` isn't late enough, use an event that is. – T.J. Crowder Oct 16 '14 at 07:45
-1

Once you have removed an attribute you cannot add it back. All you need to do is to rewrite/reassign new values to the style attribute, and this is done preferably via the .css() method, eg:

$('div').css('width','400px');

Even better: use .width() instead:

$('div').width(400);
Terry
  • 63,248
  • 15
  • 96
  • 118
  • With those method I cannot use !important rule. – Navin Rauniyar Oct 16 '14 at 07:44
  • First of all, using `!important` is a sign of bad selector choice and/or specificity. There are many cases where its use can be resolved by using other means. Otherwise you might want to consider this: http://stackoverflow.com/questions/2655925/how-to-apply-important-using-css – Terry Oct 16 '14 at 07:48