最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get clone of HTML, modify it, get HTML string without affecting DOM? - Stack Overflow

programmeradmin2浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 4

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.

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);
发布评论

评论列表(0)

  1. 暂无评论