Forum Moderators: open

Message Too Old, No Replies

Wrap an element using Javascript/DOM?

But doesn't replace anything

         

Ian2k8

5:46 am on Feb 4, 2008 (gmt 0)

10+ Year Member



Here is a div and it has a childNode span.

<div id="myDiv"><span>Hello World</span></div>

How can we wrap it with another <div></div> but doesn't replace anything? Like:

<div>
<div id="myDiv"><span>Hello World</span></div>
</div>

I had seen a similiar method here [webmasterworld.com], but it will replace the original one.

Fotiman

3:14 pm on Feb 4, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month




but it will replace the original one.

Yeah? So? That's exactly what you want to do. You want to replace this:

<div id="myDiv"><span>Hello World</span></div>

With this:


<div>
<div id="myDiv"><span>Hello World</span></div>
</div>

So:


var wrapper = document.createElement('div');
var myDiv = document.getElementById('myDiv');
wrapper.appendChild(myDiv.cloneNode(true));
myDiv.parentNode.replaceChild(wrapper, myDiv);

Ian2k8

2:11 am on Feb 5, 2008 (gmt 0)

10+ Year Member



Ok, now I know what to do.

I thought the cached .js file of one page will effect the content of the childNode of another, because the content of childNode of every page are dynamically generated by server. It looks like it has no such effect.

Thank you.

[edited by: Ian2k8 at 2:28 am (utc) on Feb. 5, 2008]