HTML DOM getAttributeNode() 方法
htmlweb developmentfront end technology更新于 2025/9/24 5:32:17
HTML DOM getAttributeNode() 用于将给定元素的属性节点作为 Attr 对象返回。使用 Attr 对象的各种属性和方法,您可以操作这些属性。
语法
以下是 getAttributeNode() 方法的语法 −
element.getAttributeNode(attributename)
其中,attributename 是一个字符串类型的强制参数,用于指定我们要返回的属性名称。
示例
让我们来看一个 getAttributeNode() 方法的示例 −
<!DOCTYPE html>
<html>
<head>
<script>
function getAttrNode(){
var a = document.getElementsByTagName("a")[0].getAttributeNode("href");
var val=a.value;
document.getElementById("Sample").innerHTML = val;
}
</script>
</head>
<body>
<h1>getAttributeNode() 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="getAttrNode()">GET</button>
<p id="Sample"></p>
</body>
</html>
输出
这将产生以下输出 −

点击 GET 按钮时 −

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

