HTML DOM 脚本集合
htmlweb developmentfront end technology更新于 2025/8/19 18:20:17
HTML DOM 脚本集合返回 HTML 文档中所有 <script> 元素的集合。
语法
以下是语法 −
document.scripts
脚本对象的属性
| 属性 | 说明 |
|---|---|
| length | 返回 <script> 元素的数量。 HTML 文档中集合中的元素。 |
script 对象的方法
| 方法 | 说明 |
|---|---|
| [index] | 返回集合中指定索引的 <script> 元素。 |
| item(index) | 返回集合中指定索引的 <script> 元素。 |
| namedItem(id) | 返回集合中指定 id 的 <script> 元素。 |
示例
让我们看一个 scripts 集合的示例 −
<!DOCTYPE html>
<html>
<head>
<style>
html{
height:100%;
}
body{
text-align:center;
color:#fff;
background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) center/cover no-repeat;
height:100%;
}
p{
font-weight:700;
font-size:1.2rem;
}
ul{
list-style-type: none;
padding:0;
}
.btn{
background:#0197F6;
border:none;
height:2rem;
border-radius:2px;
width:50%;
margin:2rem auto;
display:block;
color:#fff;
outline:none;
cursor:pointer;
}
.show{
font-size:1.5rem;
font-weight:bold;
}
</style>
</head>
<body>
<script>
console.log("script one");
</script>
<h1>DOM scripts Collection Demo</h1>
<p>Hi, There are two script elements on this page:</p>
<script>
console.log("script two");
</script>
<button onclick="show()" class="btn">Show No. Of Script</button>
<div class='show'></div>
<script>
function show() {
var scriptList = document.scripts;
document.querySelector(".show").innerHTML=scriptList.length;
}
</script>
</body>
</html>
输出
这将产生以下输出 −

点击“显示脚本数量”按钮显示脚本元素的数量。

相关文章
有用资源
html 参考教程 - 该教程包含有关 html 的更多信息:https://www.cainiaomax.com/html/

