Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I erase all inline styles with javascript and leave only the styles specified in the css style sheet?

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?

like image 871
Matt Avatar asked Aug 04 '09 20:08

Matt


People also ask

How do I remove all inline styles?

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.

How do you unset all styles in CSS?

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.

What is remove inline styles?

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.

How do you remove styles in HTML?

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.


2 Answers

$('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.

like image 135
Tyler Carter Avatar answered Oct 12 '22 17:10

Tyler Carter


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.

like image 39
Josh Crozier Avatar answered Oct 12 '22 17:10

Josh Crozier