Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have multiple data-{name} atributes in HTML5?

Is there a way to get all 3 data values from this element?

 <div id="viewport" 
    data-requires='js/base/paths'
    data-requires='js/base/dialog'
    data-requires='js/base/notifier'>

This would be really useful for a project that I am starting. With this I could load required js modules and link them to the dom. I know it might sound strange, but I'm trying something new here.

like image 350
Vlad Nicula Avatar asked Aug 14 '12 23:08

Vlad Nicula


People also ask

Can you have multiple data attributes in HTML?

Data attributes always start with “data-” then followed with a descriptive name of the data that is being stored. You can have multiple data attributes on an element and be used on any HTML element.

What are data attributes in HTML 5?

Definition and Usage. The data-* attribute is used to store custom data private to the page or application. The data-* attribute gives us the ability to embed custom data attributes on all HTML elements.

Can an attribute be applied multiple times to the same element?

It is not valid to have the same attribute name twice in an element.


3 Answers

The answer to your question is that HTML does not support multiple instances of the same property. All the typical ways that you might retrieve that attribute will only retrieve one of the three.

The usual way to solve this problem is to use a single instance of the attribute and put multiple paths as the value. For paths, they are usually separated by semi-colons.

<div id="viewport" data-requires='js/base/paths;js/base/dialog;js/base/notifier'>

And, then use code to break up the multi-valued attribute into an array.

var requiredPaths = document.getElementById("viewport").getAttribute("data-requires").split(";");
like image 70
jfriend00 Avatar answered Nov 03 '22 06:11

jfriend00


You can use more complex structures within data- attributes.

Instead of this:

<div id="viewport" 
data-requires='js/base/paths'
data-requires='js/base/dialog'
data-requires='js/base/notifier'>

you can do this:

<div id="viewport"
data-requires='["js/base/paths", "js/base/dialog", "js/base/notifier"]'>
</div>

Proof using jQuery.data() (which just retrieves the array this way: jQuery('#viewport').data('requires')) is here: http://jsfiddle.net/3StZs/

like image 42
Tadeck Avatar answered Nov 03 '22 05:11

Tadeck


You could put them all in one if you separated them by something then split them up and put them in an Array.

var arrayData = document.getElementById('viewport').getAttribute('data-requries');
var arr = arrayData.split(',');

for (i = 0; i < arr.length; i++) {
    console.log(arr[i]);
}

​ http://jsfiddle.net/S7D2D/1/

like image 6
Mark Pieszak - Trilon.io Avatar answered Nov 03 '22 05:11

Mark Pieszak - Trilon.io