views:

107

answers:

2

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.

+1  A: 

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);
bobince
+3  A: 

You 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.

CMS
Nice one, thank you.
Deniss Kozlovs