The Wayback Machine - https://web.archive.org/web/20250109062344/https://www.geeksforgeeks.org/html-dom-getnameditem-method/
Open In App

HTML DOM getNamedItem() Method

Last Updated : 30 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The DOM getNamedItem() method in HTML is used to return the attribute node from the NamedNodeMap object.

Syntax: 

namednodemap.getNamedItem( nodename )

Parameter’s Value: This method contains a single parameter nodename which is mandatory. The nodename is returned from the NamedNodeMap object. 

Return Value: It returns a Node object, which represents the attribute node with the specified name

Example: In this example, we will getNamedItem() method.

HTML
<!DOCTYPE html>
<html>

<head>
    <title>
        DOM getNamedItem() Method
    </title>
    <script>
        /* main function */
        function MyGeeks() {
            let ele = document.getElementsByTagName("button")[0];
            let item = ele.attributes.getNamedItem("onclick").value;
            document.getElementById("geeks").innerHTML = item;
        }
    </script>
</head>

<body style="text-align:center">
    <h2>DOM getNamedItem() Method</h2>
    <p>
        Click on the button to know the
        value of onclick attribute
    </p>
    <button onclick="MyGeeks()">
        Click Here!
    </button>
    <p id="geeks"></p>
</body>

</html>

Output: 

Supported Browsers: The browser supported by DOM getNamedItem() Method are listed below:  

HTML DOM getNamedItem() Method – FAQs

What does getNamedItem() return if the attribute does not exist?

If the specified attribute does not exist, getNamedItem() returns null.

Can getNamedItem() be used to retrieve data attributes?

Yes, it can retrieve any attribute by name, including data attributes like data-attribute.

Is getNamedItem() case-sensitive?

Yes, getNamedItem() is case-sensitive, meaning the attribute name must match exactly, including case.

Can getNamedItem() be used with any element?

Yes, getNamedItem() can be used with any HTML element, as it operates on the NamedNodeMap of the element’s attributes.

How does getNamedItem() interact with custom attributes?

getNamedItem() can retrieve any custom attributes, including those not predefined by HTML.


Next Article

Similar Reads

three90RightbarBannerImg