Reputation: 155
I'm trying to duplicate a <div>
element which contains a <script>
. The problem is, when I append it in the DOM, the script contained is not executed.
How can I solve it ?
Upvotes: 0
Views: 52
Reputation: 343
Generally, anything you add to the DOM will be inserted as DOM text, and scripts won't get executed. They'll need to be evaluated.
Frameworks like jquery and mootools will automatically do this for you. If you use plain js, you'll need to do this yourself.
For example:
var arr = duplicatedDiv.getElementsByTagName('script');
for (var n = 0; n < arr.length; n++)
eval(arr[n].innerHTML) //evaluate the contents of this script tag
This however is not failproof and hardly the way to go. You should never use eval()
unless you're sure there's no other way.
You have not provided the script you need to execute after the cloning of the div, but one of the possible answers is moving the required code into a seperate function which you call after cloning.
For example, if your html is this:
<div id="orig">
<p>some content</p>
<script>alert('hi');</script>
</div>
And your javascript is this:
function cloneDiv(id) {
var orig = document.getElementById(id),
clone = orig.cloneNode(true);
document.body.appendChild(clone);
}
You could change that to: HTML:
<div id="orig">
<p>some content</p>
</div>
and js:
function cloneDiv(id) {
var orig = document.getElementById(id),
var clone = orig.cloneNode(true);
document.body.appendChild(clone);
afterClone();
}
function afterClone(){
alert('hi');
}
Ofcourse this is a very simple example, and you probably need to pass some variables or references to the function, but you should get the gist.
Upvotes: 1
Reputation: 40842
The reason why it won't work is described here: Why don't cloneNode tags execute?.
You could solved that by searching for all script
tags and replace them with a new one, that way it will be executed on insert.
function cloneAndRenewScripts(element) {
var dupNode = element.cloneNode(true);
var scripts = dupNode.getElementsByTagName('script');
for( var i=0; i<scripts.length ; i++ ) {
var tmp = document.createElement('script');
tmp.textContent = scripts[i].textContent;
scripts[i].parentNode.replaceChild(tmp, scripts[i]);
}
return dupNode;
}
Here a jsfiddle demo
Upvotes: 1