If I have the following in my html:
<div style="height:300px; width:300px; background-color:#ffffff;"></div>
And this in my css style sheet:
div {
width:100px;
height:100px;
background-color:#000000;
}
Is there any way, with javascript/jquery, to remove all of the inline styles and leave only the styles specified by the css style sheet?
Approach: The jQuery attr() and removeAttr() methods are used to remove the inline style property. The attr() method sets the attribute value to empty (”). Example 1: This example uses attr() method to remove the inline style.
There is a property called all that is being proposed for resetting all CSS properties for a given element to certain CSS-wide values - the value you want to use would be unset , which resets a property to either its inherited value if it inherits by default, or otherwise, its initial value.
Using inline styles means that the styles of the elements are not given by classes or ids but it's specified within the HTML tag using the style="..." attribute. Using this feature of the HTML Cleaner you can easily remove every unwanted inline css code from your document with a single click.
Use the removeAttribute() method to remove all styles from an element, e.g. box. removeAttribute('style') . The removeAttribute method will remove the style attribute from the element.
$('div').attr('style', '');
or
$('div').removeAttr('style');
(From Andres's Answer)
To make this a little smaller, try this:
$('div[style]').removeAttr('style');
This should speed it up a little because it checks that the divs have the style attribute.
Either way, this might take a little while to process if you have a large amount of divs, so you might want to consider other methods than javascript.
Plain JavaScript:
You don't need jQuery to do something trivial like this. Just use the .removeAttribute()
method.
Assuming you are just targeting a single element, you can easily use the following: (example)
document.querySelector('#target').removeAttribute('style');
If you are targeting multiple elements, just loop 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 above / .querySelectorAll()
- IE 8 (partial) IE9 and above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With