Reputation: 3726
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.
Upvotes: 18
Views: 26483
Reputation: 67141
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/
Upvotes: 6
Reputation: 137420
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/
Upvotes: 10
Reputation: 707786
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(";");
Upvotes: 20