HTML has come a long way. It’s the most remarkable web aspect today. While it comes with a bunch of great new semantic elements with the release of HTML5, it now offers machine-readable data which browser and script can use to manipulate the DOM while displaying human-readable content.

Going back in the days where developers uses HTML4, there are only limited ways to store data and then manipulate it via JavaScript. That time developers only rely on meta elements, class, rel and profile attributes to extend data. While rev and profile are no longer included in HTML5 due to the fact that they are not that easy to use correctly, meta elements, class and rel remained in HTML5.

That’s why the HTML5 data attribute with its appended custom value was introduced for this reason. This allows us to store data for scripts and convert it in a human-readable content. Appending data for scripts to any element is really easy compared to class and rel attributes.

Custom data-attribute format is divided into parts:

  • Attribute Name – this is the name of the data attribute. Using the prefixed “data-” code you can append any string name with and at least one character long that doesn’t have any uppercase letters.
  • Attribute Value – this is the value or the content of the data attribute. Remember to always put string value.

Below is an image tag that contains data-attribute name data-name. Notice that the value was set to color. That is how you can easily include data-attribute within different types of elements.

<img src=”circle.jpg” data-name=”color”/>

Using CSS to fetch and display HTML5 Data Attributes

For this part of this article, let’s look on how we can fetch the value of the data-attribute and then display it on a particular part of the web page using CSS.

Considering the following unordered list with links inside, I have added a custom data-attribute data-nav for each respective navigation name and then use the name of the link as the value of the custom data-attribute.

<ul>
        <li>
            <a data-nav="Home" href="#">Home</a>
        </li>
        <li>
            <a data-nav="Profile" href="#">Profile</a>
       </li>
        <li>
            <a data-nav="Portfolio" href="#">Portfolio</a>
        </li>
        <li>
            <a data-nav="Contact" href="#">Contact</a>
        </li>
    </ul>

Now to display the value of the selected data-attribute, we’ll use the ::after selector to insert the content of the selected value to the right side of our document using the name of the custom data-attribute inside the attr block. We’ll give the selected a hexadecimal background color of #9b59b6 and then use opacity and CSS3 transition to show and hide the data value.  Try it yourself. I created a jsFiddle (http://jsfiddle.net/eyk3ow8g/31/)  demo.

a::after {
    content:attr(data-nav);
    position:absolute;
    right:60px;
    top:35px;
    font-size:15px;
    color:#fff;
    text-align:center;
    background-color:#9b59b6;
    display:block;
    padding:0 10px;
    width:61px;
    height:38px;
    color:#fff;
    line-height:250%;
    opacity:0;
    -webkit-transition:all .6s ;
-moz-transition:all .6s;
    transition:all .6s;
}

a:hover::after {
    opacity:1
}

Though the example might be simple, it gives you a great foundation on how you can fetch and then display the data-attribute value using CSS.

Using JavaScript to fetch and set data via HTML5 Data Attributes

For this part of this article, let’s now look on how we can use JavaScript to manipulate custom data attribute. Check out the example below.

<div id='myId' data-email="youremail@email.com">Sam's email is 
    <span id="email"></span> 
</div>
<button type="button" id="btnId" onclick="clickbtn()">Set Attribute Now</button> 

On the example above, I created a simple div with an id of myId and then set up the custom data-email attribute to youremail@email.com . Then I created a button with an id of btnId and set up an onclick event with the function clickbtn function.

Now let’s move on to the JavaScript part. Remember that browser can pull out and modify attribute via getAttribute and setAttribute function so we can use those function to modify what was set inside our custom data-attribute values.

var email;
window.onload = function(){
    email = document.getElementById("myId");
    document.getElementById("email").innerHTML = email.getAttribute("data-email");
};
function clickbtn(){    
    var old_email = email.getAttribute("data-email");
    email.setAttribute("data-email","newmail@email.com");
    document.getElementById("email").innerHTML = email.getAttribute("data-email");
}

Above codes will set a var email and then when the window loads it will fetch the id using getAttribute method and the data-email’s default value which is youremail@email.com. Next, we created a function clickbtn and then inside it pull out again the default  value of our data-email and then set up a new email using the setAttribute method. Finally we use the innerHTML method to set it up on the span via id.  See real time example here: http://jsfiddle.net/dndnqygL/12/

Using jQuery.data()

Now that we know how we can use native JavaScript to manipulate custom data-attribute let’s now look on how we can use jQuery to do the same. Basically, jQuery has jQuery.data() function that is very useful for pulling up data as well as passing custom settings for DOM.

Let’s start with our markup. Our markup will simply have a div with an id container. Inside it we’ll put text and then set up span tags to output our data attribute values via jQuery.data() function. We’ll need to set up also a button to change the value of the last name later on.

<div id="container">
 My complete name is <span></span> D. <span></span>
</div>
<button type="button" id="btnID">Set Last Name to Smith </button>

Now for our jQuery codes, we’ll create a variable holder to pull up the container id. Calling jQuery.data() function retrieves all of the element’s associated values. Our basic syntax for this will be jQuery.data( element, key, value ). Let’s look up on what’s these values are all about:

  • element – will be the DOM element that is associate with the data
  • key – will be a string element that will name the data set
  • value – will have data value itself. This can be any type of data except undefined

See codes below.

var holder = $( "#container" )[0];

jQuery.data( holder, "data", {
  firstname: "Sam",
  lastname: "Norton"
});

Next, we will create and call the setNames function. This will set the data to the span elements on our markup. Then we’ll call it right after the jQuery.data() elements.

setNames();
function setNames() {
    $( "span:first" ).text( jQuery.data( holder, "data" ).firstname );
    $( "span:last" ).text( jQuery.data( holder, "data" ).lastname );
}

Now for our final code, let’s now create an event click function by calling the button id btnID.  We also need to set the default action of the event if it was not executed by using event.prevenetDefault() method. To finally finish our codes will set jQuery data lastname to “Smith” and then call the function setNames() once again. Check out the final demo of this example here. http://jsfiddle.net/vzzscnmr/5/

$('#btnID').click(function(event){
  
   event.preventDefault() ;
   jQuery.data( holder, "data", {lastname: "Smith"});
   setNames();
});

Using dataset API

That dataset API gives us a simple way to manipulate data attributes. It can retrieve, set and delete data attribute values. Let’s look on we can use this. Let’s first create our markup.

<div id="custom" data-car="BMW"></div>

Now to retrieve the data-car attribute value we will simply use the following code.

//Retrieve the element
var element = document.getElementById("custom")
//Retrieve the car
var car = element.dataset.car

Now if you want to assign value to car you just need to set it like this:

element.dataset.car = "Honda";

One of the best thing about dataset API is widely supported among desktop and mobile browsers except with the Dinosaur browser – IE 10 or below. If you are thinking to about the fallback you might want to just use the native JavaScript codes function that was introduced above.

Conclusion

HTLM5 custom data-attrbutes are really helpful in storing, accessing and editing element’s value and can work with the DOM via JavaScript. There are a lot of ways to manipulate data and this article serves as a good foundation on how to do so.

Hope you learned something on this article. Have you use one of these methods before? Let me know what you think in the comment section?