DOM Attribute

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

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;
    }
&lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div class="my_exe"&gt;&lt;h3&gt;HTML DOM Attribute name Property&lt;/h3&gt;&lt;p&gt;Click on the below image to get it's attribute&lt;/p&gt;&lt;img id="demo" src="https://www.tutorialspoint.com/images/logo.png" alt="demo image" onclick="printAttribute()"/&gt;&lt;input type="text" id="attribute-box" placeholder="Attribute of img tag..." readonly/&gt;&lt;/div&gt;&lt;script&gt;
    function printAttribute() {
        const element = document.getElementById("demo");
        let aName = element.attributes[0].name;
        document.getElementById("attribute-box").value = aName;
    }
&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

HTML DOM Attribute Properties

The following table contains a list of DOM Attribute properties −

Sr.NoProperties & Description
1.valueThis property is used to set or get the value of an attribute.
2.specifiedIt checks whether the mentioned attribute is specified or not.
3.nameIt is used get the name of the used attribute on an element.
4.isIdThis property determines whether a HTML attribute is an 'id' attribute or not.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *