HTML DOM getElementsByTagName() 方法
htmlweb developmentfront end technology更新于 2024/5/31 9:16:17
HTML DOM getElementsByTagName() 方法用于获取文档中所有具有指定标签名称的元素集合。它将所有给定元素以 NodeList 对象的形式返回。您可以使用索引号访问返回对象中的任何元素。
返回的 HTML 集合与 DOM 树保持同步,无需在删除或添加某些元素后反复调用 getElementsByTagName() 方法。
语法
以下是 getElementsByTagName() 方法的语法 −
element.getElementsByTagName(tagname)
其中,tagname 是必需参数值,表示我们要获取的子元素的 tagname。
示例
让我们来看一个 getElementsByTagName() 方法的示例 −
<!DOCTYPE html>
<html>
<head>
<script>
function changePara() {
var p = document.getElementsByTagName("P");
p[0].innerHTML = "This text has been changed";
p[1].style.color = "red";
p[1].style.backgroundColor = "yellow";
}
</script>
</head>
<body>
<h1>getElementsByTagName() example</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua</p>
<p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat</p>
<button onclick="changePara()">CHANGE</button>
</body>
</html>
输出
这将产生以下输出 −

单击"更改"按钮时

在上面的例子中−
我们创建了两个没有与之关联的属性的段落−
<p>Lorem ipsum dolor sat amet,consectetur adipiscing elit,sed do eiusmod tempor inciditunt ut laboure et dolore magna aliqua</p> <p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat</p>
然后,我们创建了一个按钮 CHANGE,当用户点击该按钮时,它将执行 changePara() −
<button onclick="changePara()">CHANGE</button>
changePara() 方法使用 document 对象上的 getElementsByTagName() 方法获取两个 <p> 元素作为 nodeListObject,并将其赋值给变量 p。使用索引号,我们更改第一段的文本,并对第二段应用一些样式 −
function changePara() {
var p = document.getElementsByClassName("PARA1");
p[0].innerHTML = "This text has been changed";
p[1].style.color = "red";
p[1].style.backgroundColor = "yellow";
}
相关文章
有用资源
html 参考教程 - 该教程包含有关 html 的更多信息:https://www.cainiaomax.com/html/

