I have some HTML code like this:
<div style="background:red;width:900px;height:200px" id="wrap">
<div id="inner" style="width:300px;float:left">
...
</div>
</div>
I need to:
1) Remove "styles" attribute and maybe some others
2) Leave only "id" attribute
4) Get resulting HTML as a string
5) All of this without affecting the original markup
I have tried cloning them as javascript object, but manipulations on them affect DOM.
I have some HTML code like this:
<div style="background:red;width:900px;height:200px" id="wrap">
<div id="inner" style="width:300px;float:left">
...
</div>
</div>
I need to:
1) Remove "styles" attribute and maybe some others
2) Leave only "id" attribute
4) Get resulting HTML as a string
5) All of this without affecting the original markup
I have tried cloning them as javascript object, but manipulations on them affect DOM.
Share Improve this question asked Oct 14, 2009 at 7:33 Deniss KozlovsDeniss Kozlovs 4,8092 gold badges30 silver badges36 bronze badges2 Answers
Reset to default 4You could clone your #wrap
element, modify the as you desire, and append it to a new element, that doesn't exists on the DOM:
var cloned = $('#wrap').clone(),
container = $('<div></div>');
cloned.find('div').andSelf().removeAttr('style');
alert(container.append(cloned).html());
Check the above example here.
It sounds like you had the right approach, clone-and-alter should definitely work. I don't know why your code was altering the original DOM, but this doesn't:
var el= document.getElementById('wrap');
el= el.cloneNode(true);
el.removeAttribute('style');
el.getElementsByTagName('div')[0].removeAttribute('style');
// Get full markup (like outerHTML, but better-supported)
//
var outer= document.createElement('div');
outer.appendChild(el);
alert(outer.innerHTML);