HTML DOM Document scripts

Examples

Number of <script> elements in the document:

document.scripts.length;
Try it Yourself »

Return the content of the first <script> element:

document.scripts[0].text;
Try it Yourself »

Return the content of the first <script> element:

document.scripts.item(0).text;
Try it Yourself »

More examples below.


Description

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

The scripts property returns an HTMLCollection.

The scripts property is read-only.

See Also:

The Script Object.


HTMLCollection

An HTMLCollection is an array-like collection (list) of HTML elements.

The elements in a collection can be accessed by index (starts at 0).

The length Property returns the number of elements in the collection.


Syntax

document.scripts

Properties

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

Methods

Method Description
[index] Returns the element with the specified index (starts at 0).
Returns null if the index is out of range.
item(index) Returns the element with the specified index (starts at 0).
Returns null if the index is out of range.
namedItem(id) Returns the element with the specified id.
Returns null if the id does not exist.

Return Value

Type Description
ObjectAn HTMLCollection Object.
All <script> elements in the document.
The elements are sorted as they appear in the document.


More Examples

Return the content of the <script> element with id="myScript":

document.scripts.namedItem("myScript").text;
Try it Yourself »

Loop over all <script> elements and output each id:

const collection = document.scripts;
let text = "";
for (let i = 0; i < collection.length; i++) {
  text += collection[i].id + "<br>";
}
Try it Yourself »


Browser Support

document.scripts is a DOM Level 2 (2001) feature.

It is fully supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes 9-11


Copyright 1999-2023 by Refsnes Data. All Rights Reserved.