HTML - DOM Attribute name Property



HTML DOM attribute name property is used get the name of the used attribute on an element. The name property is a read-only property which means this property cannot alter the attributes of HTML elements.

Syntax

attribute.name

Return value

The name property return the name of attribute for specified index.

Examples of HTML DOM Attribute 'name' Property

Here are some example codes that illustrate the how to use 'name' property in JavaScript and HTML.

Get the name of first Attribute

The Following code shows how to use name attribute to get name of attributes of HTML tags.

<!DOCTYPE html>
<html>

<head>
    <title>HTML DOM Attribute name Property</title>
</head>

<body>
    <h3>HTML DOM Attribute name Property</h3>
    <p>
        The name property of DOM returns 
        the name of an attribute
    </p>

    <div id="demo"></div>

    <script>
        const element = document.getElementById("demo");

        // This will select name of first attribute of div
        let aName = element.attributes[0].name;
        // Pass the name to inside of div tag
        document.getElementById("demo").innerHTML = aName;
    </script>
</body>

</html>

Get name of all Attributes

Here we will run a simple for loop to get name of all the attributes of a HTML element.

<!DOCTYPE html>
<html>

<head>
    <title>HTML DOM Attribute name Property</title>
</head>

<body>
    <h3>HTML DOM Attribute name Property</h3>
    <p>
        The name property of DOM returns 
        the name of attributes
    </p>

    <div id="demo" 
         class="exampleClass" 
         data-info="someData">
    </div>

    <script>
        const element = document.getElementById("demo");

        // Initialize an empty array to hold attribute names
        let attributeNames = [];

        // Loop through all attributes of the element
        for (let i = 0; i < element.attributes.length; i++) {
            attributeNames.push(element.attributes[i].name);
        }

        // Join the attribute names with commas 
        // and pass them inside the div tag
        document.getElementById("demo").innerHTML = 
        attributeNames.join(", ");
    </script>

</body>

</html>

Supported Browsers

Property Chrome Edge Firefox Safari Opera
name Yes Yes Yes Yes Yes
html_dom.htm
Advertisements