简体   繁体   中英

How to append script tag to a div tag which is dynamically generate by javascript

I create a dynamical tag with id "video1" inside the static tag with id "videos":

document.getElementById("videos").innerHTML = '<div id="video1"></div>';

But when I want to append another script tag, I failed.

The following is my code to append that tag:

var s = document.createElement("script");
s.id = "scriptId"; //script tag's id
document.getElementById("video1").appendChild(s);

The above code works for static tag, but it doesn't work for the dynamical generated tag video1. So is there any way I can append a script tag to an another tag which is also dynamically generated by javascript?

Thanks.

Instead, append it to the head:

var s = document.createElement("script");
s.id = "scriptId"; //script tag's id
document.getElementsByTagName("head")[0].appendChild(s);

You can also use eval(s.text) to evaluate the text content of the script

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM