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.
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.
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.
It is not valid to have the same attribute name twice in an element.
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(";");
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/
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With