HTML DOM getAttributeNode() method


The HTML DOM getAttributeNode() is used for returning the a given element attribute node as an Attr object. Using the various Attr object properties and methods, you can manipulate the attributes.

Syntax

Following is the syntax for getAttributeNode() method −

element.getAttributeNode(attributename)

Here, the attributename is a mandatory parameter of type string that specifies the attribute name we want to return.

Example

Let us look at an example of the getAttributeNode() method −

<!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>

Output

This will produce the following output −

On clicking the GET button −

In the above example −

We have first created an anchor element with href attribute value set to “https://www.google.com”.

<a href="https://www.google.com">GOOGLE</a>

We then created a button GET that will execute the getAttrNode() on being clicked by the user −

<button onclick="getAttrNode()">GET</button>

The getAttrNode() method uses the getElementByTagName() method to get the first anchor element in out HTML document. It then uses the getAttributeNode(“href”) method with parameter value “href”.

The getAttributeNode() method returns an attr object representing the href attribute and assigns it to variable a. We then assign the href attribute value using the attr object “value” property to variable val. The href attribute value obtained is displayed in the paragraph with id “Sample” using its innerHTML property −

function getAttrNode(){
   var a = document.getElementsByTagName("a")[0].getAttributeNode("href");
   var val=a.value;
   document.getElementById("Sample").innerHTML = val;
}
raja
Published on 09-Aug-2019 11:39:00
Advertisements