Latest web development tutorials
 

HTML DOM scripts Collection

< Document Object

Example

Find out how many <script> elements there are in the document:

var x = document.scripts.length;

The result of x will be:

2
Try it Yourself »

More "Try it Yourself" examples below.


Definition and Usage

The scripts collection returns a collection of all <script> elements in the document.

Note: The elements in the collection are sorted as they appear in the source code.

Tip: Also look at the Script Object.


Browser Support

The numbers in the table specify the first browser version that fully supports the collection.

Collection
scripts Yes Yes 9.0  Yes Yes

Syntax

document.scripts

Properties

Property Description
length Returns the number of <script> elements in the collection.

Note: This property is read-only

Methods

Method Description
[index] Returns the <script> element from the collection with the specified index (starts at 0).

Note: Returns null if the index number is out of range
item(index) Returns the <script> element from the collection with the specified index (starts at 0).

Note: Returns null if the index number is out of range
namedItem(id) Returns the <script> element from the collection with the specified id.

Note: Returns null if the id does not exist

Technical Details

DOM Version: Core Level 3 Document Object
Return Value: An HTMLCollection Object, representing all <script> elements in the document. The elements in the collection are sorted as they appear in the source code

Examples

More Examples

Example

[index]

Get the contents of the first <script> element (index 0) in the document:

var x = document.scripts[0].text;

The result of x will be:

document.write("Hello World!");
Try it Yourself »

Example

item(index)

Get the contents of the first <script> element (index 0) in the document:

var x = document.scripts.item(0).text;

The result of x will be:

document.write("Hello World!");
Try it Yourself »

Example

namedItem(id)

Get the contents of the <script> element with id="myScript" in the document:

var x = document.scripts.namedItem("myScript").text;

The result of x will be:

function myFunction() { var x = document.scripts.namedItem("myScript").text; document.getElementById("demo").innerHTML = x; }
Try it Yourself »

Example

Loop through all <script> elements in the document, and output the id of each script:

var x = document.scripts;
var txt = "";
var i;
for (i = 0; i < x.length; i++) {
    txt = txt + x[i].id + "<br>";
}

The result of txt will be:

myFirstScript
mySecondScript
Try it Yourself »

Related Pages

JavaScript reference: HTML DOM Script Object

HTML tutorial: HTML Scripts

HTML reference: HTML <script> tag


< Document Object