HTML DOM getAttribute() 方法
htmlweb developmentfront end technology更新于 2024/5/31 10:52:17
HTML DOM getAttribute() 方法用于获取或设置与特定 HTML 元素关联的属性。如果元素不包含给定的属性,则返回 null 或空字符串。
语法
以下是 getAttribute() 方法的语法 −
element.getAttribute(attributename)
其中,attributename 为字符串类型,且为必填参数。它表示要获取其值的属性名称。
示例
让我们来看一个 getAttribute() 方法的示例 −
<!DOCTYPE html>
<html>
<head>
<script>
function getAttr() {
var a = document.getElementsByTagName("a")[0].getAttribute("href");
document.getElementById("Sample").innerHTML = a;
}
</script>
</head>
<body>
<h1>getAttribute() example</h1>
<a href="https://www.google.com">GOOGLE</a>
<p>Get the href attribute value of the above link by clicking the below button</p>
<button onclick="getAttr()">GET</button>
<p id="Sample"></p>
</body>
</html>
输出
这将产生以下输出 −

点击 GET 按钮时 −

在上面的例子中 −
我们首先创建了一个锚元素,并将 href 属性值设置为 https://www.google.com −
<a href="https://www.google.com>GOOGLE</a>
然后,我们创建了一个按钮 GET,当用户点击按钮时,它会执行 getAttr() 方法 −
<button onclick="getAttr()">GET</button>
getAttr() 方法使用 document 对象的 getElementByTagName() 属性获取 HTML 文档中的第一个 <a> 元素。
然后,它使用 getAttribute() 方法获取 href 属性值,并将该值赋给变量 a。然后,该值会使用其 innerHTML 属性显示在 id 为"Sample"的段落中。−
function getAttr() {
var a = document.getElementsByTagName("a")[0].getAttribute("href");
document.getElementById("Sample").innerHTML = a;
}
相关文章
有用资源
html 参考教程 - 该教程包含有关 html 的更多信息:https://www.cainiaomax.com/html/

