How to use getAttribute() and setAttribute() Method In HTML

HTML DOM getAttribute() can be used to get the stored data from the attribute. It will either return a null or an empty string if the asked attribute does not exist. HTML DOM setAttribute() can be used to modify the value of any existing attribute or to add a new attribute. 

Example: Implementation to show how to read the values of these attributes with JavaScript is quite simple.

HTML




<!DOCTYPE html>
<html>
 
<head>
    <title>HTML5 Custom attributes</title>
</head>
 
<body>
    <h3>Welcome To GFG</h3>
    <ul>
        <li onclick="showPosition(this)"
            id="geek1" data-position="winner">
            Geek1
        </li>
 
        <li onclick="showPosition(this)"
            id="geek2" data-position="runner up">
            Geek2
        </li>
 
        <li onclick="showPosition(this)"
            id="geek3" data-position="third">
            Geek3
        </li>
 
        <li onclick="showPosition(this)"
            id="geek4" data-position="lost">
            Geek4
        </li>
    </ul>
 
    <script src="custom_attributes.js"></script>
</body>
 
</html>


Javascript




// This JavaScript file will handle the custom
// attributes which will be accessed using getAttribute().
// We will use this to create an alert whenever a list item is clicked.
 
function showPosition(runner) {
    var position = runner.getAttribute("data-position");
    alert("The " + runner.innerHTML + " is " + position + ".");
}


Output:

Using getAttribute() and setAttribute() Method Example Output

What are custom attributes in HTML5 ?

Custom attributes are attributes that are not part of the standard HTML5 attributes but are explicitly created. They allow us to add our information to HTML tags. These attributes store private information specific to a page or application, providing a way to add custom data to HTML elements

Any attribute whose name starts with data- is a custom attribute. The data-* attributes allow us to embed custom attributes on all HTML elements. These are completely ignored by the user. The data stored can be used in JavaScript of the page. We can also use these data attributes to style our elements.

Syntax:

<element data-*="value">

Similar Reads

Two parts of the custom Attributes

...

Using getAttribute() and setAttribute() Method

HTML DOM getAttribute() can be used to get the stored data from the attribute. It will either return a null or an empty string if the asked attribute does not exist. HTML DOM setAttribute() can be used to modify the value of any existing attribute or to add a new attribute....

Data Attribute Access with Dataset

...

CSS Styling with Custom Attributes

...