Open In App

What’s the difference between element value and data attribute ?

Improve
Improve
Like Article
Like
Save
Share
Report

The element value attribute specifies the default value of the HTML element whereas the data attribute allows you to store extra data to tags in HTML when no other HTML attribute can do so.

Element value: The HTML element is the collection of start and end tags with the content inserted in between them.

Example: In this example, we will use element value.

HTML




<!DOCTYPE html> 
<html>
<body>
   <label>Website: </label>
   <input type=“text”
          value="GeeksForGeeks"/>   
</body>
</html>


Output:

Element value

Data Attribute: Data Attributes allow you to add your own information to tags in HTML. Even though the name suggests otherwise, these are not specific to HTML5 

Example: In this example, we will use data attributes.

HTML




<!DOCTYPE html>
<html>
<head>
    <script>
        function showDetails(vehicle) {
            let vehiclePrice =
                vehicle.getAttribute("data-vehicle-price");
            alert(vehicle.innerHTML
                + " is of cost " + vehiclePrice + ".");
        }
    </script>
    <style>
        h1 {
            color: green;
        }
        li {
            margin-top: 5px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <h1>Vehicle</h1>
    <p>Click on a vehicle to see how much it Cost:</p>
    <ul>
        <li onclick="showDetails(this)"
            id="Bike"
            data-vehicle-price="Rs. 80,000">
                Bike
          </li>
        <li onclick="showDetails(this)"
            id="Car"
            data-vehicle-price="Rs. 7,00,000 ">
                   Car
          </li>
        <li onclick="showDetails(this)"
            id="Truck"
            data-vehicle-price="Rs. 3,00,000 ">
                Truck
          </li>
    </ul>
</body>
</html>


Output:

Element Value

Data Attribute

The element value can be implemented using HTML elements <input>,

<button>,<meter>,<li>,<option>,<progress>and <param> elements only.

The data attribute can be used with all HTML elements.

It is used differently for different elements. For example, the <button>,<input> elements values specifies the initial value of the element.  

For <param> elements, the value attribute specifies the value of the parameter. 

It is used to define custom data attributes and to store custom data, private to the page or application.
For element value, we don’t need to give any name to it. The value must be a string. The attribute name cannot have any uppercase letters, and must be at least one character long and the prefix with ‘data-‘.


Last Updated : 01 Jun, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads