Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Remove style attributes from ALL elements

Tags:

html

jquery

I know how to remove attribute from a single element, there are already some posts about that:

$("div.preview").removeAttr("style");

This is html code:

<div class="preview" style="background-color:white">
   <p>Some text<span style="font-size:15px;">some text</span></p>
   some more code
</div>

The problem is that this will remove style attribute only from preview div. I want to remove from all elements inside that div. This is just as example, in real scenario there will be more extensive html.

Is there any short way to do that?

UPDATE: Great, I know now how to do it. But what if html is sent to function as string stored in variable. So instead of

$("div.preview") 

I have

var string = '<div class="preview"><p style='font-size:15px;'>....</p><div>'

Is there any way saying something like that the below?

$(string).find(*).removeAttr("style");
like image 311
user1324762 Avatar asked Mar 29 '13 14:03

user1324762


1 Answers

You can use the wildcard selector * to select everything underneath div.preview.

jsFiddle

$('div.preview *').removeAttr('style');

Update

RE: your related question, if we had a string instead of DOM elements. We could convert them into jQuery objects, remove the attribute as above and then convert them back (if desired).

jsFiddle

// jQuery extension to get an element's outer HTML
// http://stackoverflow.com/a/2419877/1156119
jQuery.fn.outerHTML = function(s) {
    return s
        ? this.before(s).remove()
        : jQuery("<p>").append(this.eq(0).clone()).html();
};

var string = '<div class="preview"><p style="font-size:15px;">....</p><div>'
var elements = $(string);
elements.find('*').removeAttr('style');

var withoutStyles = elements.outerHTML();
alert(withoutStyles);
like image 118
Daniel Imms Avatar answered Sep 21 '22 03:09

Daniel Imms