JavaScript获取页面所有脚本元素|Document scripts 集合

Document 对象参考手册


定义与用法

scripts 集合返回文档中所有 <script> 元素的集合。

提示: 元素在集合中的排序是它们在源代码中的顺序。

提示: 相关内容 Script 对象


语法格式

document.scripts


示例代码

查看文档中有多少个 <script> 元素:

var x = document.scripts.length;

亲自试试


浏览器支持

对象Google ChromeInternet ExplorerFirefoxSafariOpera
scriptsYesYes9.0 YesYes

表格中的数字表示支持该集合的第一个浏览器的版本号。


属性

属性描述
length返回集合中 <script> 元素的个数。

提示: 这是一个只读属性。

方法

方法描述
[index]返回集合中指定索引(从 0 开始)的 <script> 元素。

提示: 如果索引值超出范围返回 null。
item(index)返回集合中指定索引(从 0 开始)的 <script> 元素。

提示: 如果索引值超出范围返回 null。
namedItem(id)回集合中指定 id 的 <script> 元素。

提示: 如果 id 不存在返回 null。

技术细节

DOM 版本:Core Level 3 Document Object
返回值:一个 HTMLCollection 对象, 表示文档中所有的 <script> 元素。集合中元素的排序是根据源码中的顺序排列的。

更多示例

[index]

获取文档中第一个(索引为 0) <script> 元素的内容:

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

亲自试试


item(index)

获取文档中第一个(索引为 0) <script> 元素的内容:

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

亲自试试


namedItem(id)

获取 id=”runoon” 的 <script> 元素的内容:

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

亲自试试


遍历文档中所有的 <script> 元素,并输出每个 <script> 元素的 id:

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

亲自试试


相关文章

JavaScript 参考手册: HTML DOM Script 对象

HTML 教程: HTML 脚本

HTML 参考手册: HTML <script> 标签


Document 对象参考手册


相关