HTML DOM getAttributeNode() 方法

WBOY
WBOY 转载
2023-08-26 13:21:10 773浏览

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>

输出

这将产生以下输出 -

HTML DOM getAttributeNode() 方法

单击“获取”按钮时 -

HTML DOM getAttributeNode() 方法

在上面的示例中 -

我们首先创建了一个锚元素,其 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 DOM getAttributeNode() 方法的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除