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");
You can use the wildcard selector *
to select everything underneath div.preview
.
jsFiddle
$('div.preview *').removeAttr('style');
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);
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