How can I remove all inline styles using javascript and leave only the styles specified in the css stylesheet?

If in my html there is the following:

<div style="height:300px; width:300px; background-color:#ffffff;"></div> 

And this is in my CSS stylesheet:

 div { width:100px; height:100px; background-color:#000000; } 

Is there a way, with javascript / jquery, to remove all inline styles and leave only the styles specified in the CSS stylesheet?

+82
javascript jquery css inline
Aug 04 '09 at 20:14
source share
7 answers

$('div').attr('style', '');

or

$('div').removeAttr('style'); (From Andres answer )

To make it a little smaller, try the following:

$('div[style]').removeAttr('style');

This should speed it up because it checks that the div has a style attribute.

In any case, it may take a little time to process if you have a large number of divs, so you may consider other methods than javascript.

+143
Aug 04 '09 at 20:17
source share
 $('div').removeAttr('style'); 
+20
Aug 04 '09 at 20:35
source share

Normal JavaScript:

You do not need jQuery to do something trivial like this. Just use the .removeAttribute() method.

Assuming you are just targeting one element, you can easily use the following: (example)

 document.querySelector('#target').removeAttribute('style'); 

If you are targeting multiple elements, simply swipe through the selected collection of elements: (example)

 var target = document.querySelectorAll('div'); Array.prototype.forEach.call(target, function(element){ element.removeAttribute('style'); }); 

Array.prototype.forEach() - IE9 and higher / .querySelectorAll() - IE 8 (partial) IE9 and higher.

+17
Sep 18 '14 at 4:11
source share

I used the $('div').attr('style', ''); method $('div').attr('style', ''); , and it did not work in IE8.

I inferred the style attribute using alert() , and it did not remove the inline styles.

.removeAttr finished doing the trick in IE8.

+3
Sep 21 '11 at 19:09
source share

If you just need to remove the style element, then:
element.style.cssText = null;
That should do good. Hope this helps!

+2
Jun 28 '16 at 14:29
source share

This can be done in two steps:

1: select the item you want to change using tag, id, class, etc.

var element = document.getElementsByTagName('h2')[0];

  1. remove style attribute

element.removeAttribute('style');

+1
Dec 20 '14 at 22:30
source share

You can also try to list css in the stylesheet as important!

-2
Jan 07 '10 at 23:30
source share



All Articles