1

I have a code like this:

var myscript = document.createElement('script');
myscript.setAttribute('src','codescript.js');
document.head.appendChild(myscript);

The result is:

<head>
  <script src="codescript.js"></script>
</head>

Well, how do I change the code.I'm hoping to put the script into a DIV tag which will be more specific.

For example:

<head></head>

<body>
  <div id="this">
    <script src="codescript.js"></script>
  </div>
</body>
2
  • you want the content of script into the div? Commented May 10, 2016 at 7:25
  • Just put the script code in a div tag Commented May 10, 2016 at 7:29

2 Answers 2

3

Try this:

var myscript = document.createElement('script');
myscript.setAttribute('src','codescript.js');

var div = document.getElementById('this');
div.appendChild(myscript);

document.getElementById: Get the element with the specified id which is passed to that function as the first parameter.

Sign up to request clarification or add additional context in comments.

Comments

0

With jQuery, you can simply use $.getScript('codescript.js'); to load code.

See https://api.jquery.com/jQuery.getScript/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.