I want to add a element into the existing DOM to have the javascript code run.
I did this with YUI:
var scriptNode = Y.Node.create('<script type="text/javascript" charset="utf-8">alert("Hello world!");<\/script>');
var headNode = Y.one('head');
headNode.append(scriptNode);
It’s successfully added to the DOM but it doesn’t give me an alert.
Someone knows what the problem is?
I have no idea how YUI’s
Node.create()function works, so no comment on that. But a simple cross-browser script is:The try..catch block is necessary as most browsers like the first method but some don’t and throw an error. The second method covers those. You can also simply eval the code, which is more or less equivalent and what some libraries do.