HTML DOM Document scripts
示例
文件中 <script> 元素的數量
document.scripts.length;
自己動手試一試 »
返回第一個 <script> 元素的內容
document.scripts[0].text;
自己動手試一試 »
返回第一個 <script> 元素的內容
document.scripts.item(0).text;
自己動手試一試 »
更多示例見下文。
描述
scripts
屬性返回文件中所有 <script> 元素的集合。
scripts
屬性返回一個 HTMLCollection。
scripts
屬性是隻讀的。
另請參閱
HTMLCollection
HTMLCollection 是一個類陣列的 HTML 元素集合(列表)。
length 屬性 返回集合中元素的數量。
元素可以透過索引訪問(從 0 開始)。
HTMLCollection 是即時的。當文件更改時它會自動更新。
語法
document.scripts
屬性
屬性 | 描述 |
length | 集合中 <script> 元素的數量。 |
方法
方法 | 描述 |
[index] | 返回具有指定索引(從 0 開始)的元素。 如果索引超出範圍,則返回 null 。 |
item(index) | 返回具有指定索引(從 0 開始)的元素。 如果索引超出範圍,則返回 null 。 |
namedItem(id) | 返回具有指定 id 的元素。 如果 id 不存在,則返回 null 。 |
返回值
型別 | 描述 |
物件 | 一個 HTMLCollection 物件。 文件中所有的 <script> 元素。 元素按其在文件中出現的順序排序。 |
更多示例
遍歷所有 <script> 元素並輸出每個 id
const collection = document.scripts;
let text = "";
for (let i = 0; i < collection.length; i++) {
text += collection[i].id + "<br>";
}
自己動手試一試 »
瀏覽器支援
document.scripts
是 DOM Level 2 (2001) 的特性。
所有瀏覽器都完全支援。
Chrome | Edge | Firefox | Safari | Opera | IE |
是 | 是 | 是 | 是 | 是 | 9-11 |