Javascript Reference - HTML DOM Script Object








The Script object represents an HTML <script> element.

Script Object Properties

Property Description
async whether a script should be executed asynchronously
charset Sets or gets the charset attribute of a script
crossOrigin Sets or gets the the CORS settings of a script
defer Sets or gets whether a script should be defered till the page has finished parsing
src Sets or gets the src attribute of a script
text Sets or gets the contents of script element
type Sets or gets the type attribute of a script




Standard Properties and Events

The Script object supports the standard properties and events.

Example

We can access a <script> element by using getElementById().


<!DOCTYPE html>
<html>
<body>
<script id="myScript" src="demo_script_src.js"></script>
<button onclick="myFunction()">test</button>
<p id="demo"></p>
<script>
function myFunction() {<!--  w ww . jav  a 2s . c om-->
    var x = document.getElementById("myScript").src;
    document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>

The code above is rendered as follows:





Example 2

We can create a <script> element by using the document.createElement() method.


<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">test</button>
<script>
function myFunction() {<!--   www.  java  2  s  .c  o  m-->
    var x = document.createElement("SCRIPT");
    var t = document.createTextNode("console.log('Hello World!')");
    x.appendChild(t);
    document.body.appendChild(x);
}
</script>

</body>
</html>

The code above is rendered as follows: