HTML - DOM Attribute (Attr)



The attribute interface in the Document Object Model (DOM) represents attributes of an element as an object. And, this object represents an HTML attribute, through which we can control the functionality of HTML elements.

The attributes of an element are stored in an array-like unordered collection called NamedNodeMap. You can access nodes of this array using its name or index. The indexing starts from 0.

For example, the src attribute of an <img> element defines the path to the image to be displayed. Let's see how to get the name of id attribute −

HTML DOM Attribute name Property

HTML DOM Attribute name Property

Click on the below image to get it's attribute

image

Example

The code for above example is given below −

<!DOCTYPE html>
<html>
<head>
    <title>HTML DOM Attribute name Property</title>
    <style>
        .my_exe{
            width: 95%;
            padding: 10px;
            margin: 5px auto;
            background-color: rgb(197, 245, 221);
            border-radius: 10px;
            box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px;
            font-family: sans-serif;
        }
        .my_exe h3, .my_exe p, .my_exe img{
            text-align: center;
            justify-content: center;
            align-items: center;
        }
        .my_exe img{
            border: 1px solid green;
            border-radius: 5px;
            cursor: pointer;
            padding: 10px;
        }
        .my_exe input{
            display: block;
            width: 350px;
            padding: 10px;
            font-size: 18px;
            border-radius: 5px;
            outline: none;
            border: none;
            display: flex;
            margin: 10px auto;
        }
    </style>
</head>
<body>
    <div class="my_exe">
        <h3>HTML DOM Attribute name Property</h3>
        <p>Click on the below image to get it's attribute</p>
        <img id="demo" src="https://www.tutorialspoint.com/images/logo.png" alt="demo image" onclick="printAttribute()"/>
        <input type="text" id="attribute-box" placeholder="Attribute of img tag..." readonly/>
    </div>

    <script>
        function printAttribute() {
            const element = document.getElementById("demo");
            let aName = element.attributes[0].name;
            document.getElementById("attribute-box").value = aName;
        }
    </script>
</body>

</html>

HTML DOM Attribute Properties

The following table contains a list of DOM Attribute properties −

Sr.No Properties & Description
1. value

This property is used to set or get the value of an attribute.

2. specified

It checks whether the mentioned attribute is specified or not.

3. name

It is used get the name of the used attribute on an element.

4. isId

This property determines whether a HTML attribute is an 'id' attribute or not.

Advertisements