Passing Data Through data Attribute

Posted By : Sushrita Banerjee | 29-Dec-2014

1. Intoduction :

HTML 5 allows us to pass any custom string data through data-* attribute to any HTML element. It consists of 2 parts,
 

i) Attribute Name - 
Attribute name should be prefixed with 'data-' and must be one char long. It should not contain any Uppercase char.
 

ii) Attribute Value -
Any string. (may be JSON value also).

Example -

 <div data-device="mobile">
        <!-- Mobile content -->
 </div>

 

2. Use :

We can use it to store any custom or private data which can not be stored in another element and must be hidden from user. Any required data which should be used in website can also be passed thought this attribute.
    
We should aoid using this when data is visible or can be stored in any element, like 

 <span data-time="13:00">1pm<span> 
 

is worse cause we can use it like,

 <time datetime="13:00">1pm</time>

 

3. With CSS :

Using data-* attribute with css we can hide the specific code when viewed on desktop. Although this is inappropriate, but can be useful in some cases like if you want some code to view only on mobile.

Example -

 div[data-device="mobile"] {  
          display:none;  
    }

 

4. With Javascript :

We can use data-* attribute with javascript to get or set the data.

Example -

 <div id="plant" data-fruit="10" data-plant-height="2m"> </div>

 

    1st Method :-

 <script>
    //Getting data from data-* attribute
    var p = document.getElementById("plant");
    var fcount = p.getAttribute("data-fruit");
    //Setting data to data-* attribute
    p.setAttribute("data-fruit","6");
    // Select all elements with a 'data-flowering' attribute
    document.querySelectorAll('[data-fruit]');
</script>

 

    2nd Method (DataSet Method) :-

   <script>
    //Getting data from data-* attribute
    var p = document.getElementById("plant");
    var fcount = p.dataset.fruit;
    var height = p.dataset.plantHeight;   // Note here, data-plant-height --> plantHeight.
    //Setting data to data-* attribute
    p.dataset.plantHeight = "3m";
  </script>

 

5. With jQuery :

We can also retreive data from data-* attribute by jQuery.

Example -

<a class="abtn" href="abc.html" data-info="Search Engine" data-jsondata='{"keyn":"valuen"}'>
    Google
</a>

<script>
$(".abtn").click(function(){
    var info = $(this).attr("data-info");
    console.log("Info : ",info);
});
</script>

 

6. Browser Support :

All modern browsers support data-* attribute. If data-* attribute is used for styling purpose then you have to check the browser support for CSS3. And if jQuery 1.4 or aove version is used then jQuery's data Object will also be accessible.

 

Thanks

About Author

Author Image
Sushrita Banerjee

Sushrita is an experienced UI developer with experience and capabilities to build compelling UI's for Web and Mobile Applications.

Request for Proposal

Name is required

Comment is required

Sending message..