HTML DOM getNamedItem() method

HTMLWeb DevelopmentFront End Technology

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.


Following is the syntax for the getNamedItem() method −


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


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

<!DOCTYPE html>
<h1>getNamedItem() example</h1>
USERNAME: <input type="text" name="USR">
<button onclick="attrValue()">GET</button>
<p id="Sample"></p>
   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;


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.

Published on 09-Aug-2019 12:03:15