Can’t append element

  1. Home
  2. javascript
  3. Can’t append element

Any idea why the piece of code below does not add the script element to the DOM?

var code = "<script></script>";
$("#someElement").append(code);

First answer

I’ve seen issues where some browsers don’t respect some changes when you do them directly (by which I mean creating the HTML from text like you’re trying with the script tag), but when you do them with built-in commands things go better. Try this:

var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = url;
$("#someElement").append( script );

From: JSON for jQuery

Second answer

It is possible to dynamically load a JavaScript file using the jQuery function getScript

$.getScript('http://www.whatever.com/shareprice/shareprice.js', function() {
  Display.sharePrice();
});

Now the external script will be called, and if it cannot be loaded it will gracefully degrade.

Third answer

What do you mean “not working”?

jQuery detects that you’re trying to create a SCRIPT element and will automatically run the contents of the element within the global context. Are you telling me that this doesn’t work for you? –

$('#someElement').append('<script>alert("WORKING");</script>');

Edit: If you’re not seeing the SCRIPT element in the DOM (in Firebug for example) after you run the command that’s because jQuery, like I said, will run the code and then will delete the SCRIPT element – I believe that SCRIPT elements are always appended to the body… but anyway – placement has absolutely no bearing on code execution in this situation.

Reprint:https://stackoverflow.com/questions/610995/cant-append-script-element
Spread the love

Related articles

Comments are closed.