HTML DOM getNamedItem() method


The HTML DOM getNamedItem() method is used for getting the attribute node with a given name as a NamedNodeMap object. To get that specific attribute node we have to call this method only upon the attributes property since the attribute property returns a list from which we can filter a specific attribute using getNamedItem() method.

Syntax

Following is the syntax for the getNamedItem() method −

namednodemap.getNamedItem(nodename)

Here, nodename is a mandatory parameter value of type string indicating the name of the node present in the namedNodeMap.

Example

Let us look at an example for the getNamedItem() method −

Live Demo

<!DOCTYPE html>
<html>
<body>
<h1>getNamedItem() example</h1>
USERNAME: <input type="text" name="USR">
<br><br>
<button onclick="attrValue()">GET</button>
<p id="Sample"></p>
<script>
   function attrValue() {
      var usr = document.getElementsByTagName("input")[0];
      var val = usr.attributes.getNamedItem("type").value;
      document.getElementById("Sample").innerHTML = "The type attribute value for the input field is: "+val;
   }
</script>
</body>
</html>

Output

This will produce the following output −

On clicking the GET button −

In the above example −

We have first created an input field with type=”text” and name=”USR”.

USERNAME: <input type="text" name="USR">

We have then created the button GET that will execute the method attrValue() on being clicked by the user −

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

The attrValue() method uses the getElementsByTagName() method to get the input element and assigns it to variable usr. We then use the attributes property which returns the collection of all attributes as namedNodeMap object. Calling the getNamedItem() method upon the attributes property returns only that specific attribute node.

Using the value property on the specific node returned by the getNamedItem(), we get that attribute value and assign it to variable val. This value is then displayed in the paragraph with id “Sample” using its innerHTML property.

Updated on: 19-Feb-2021

102 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements