In many modern browsers, we have access to these special attributes through the penis .dataset on site Node . Unfortunately, this is not an accepted standard, and therefore we do not see that it is accepted in the whole spectrum. Fortunately, in every major browser has partial support in the fact that these attributes can be accessed using common techniques such as getAttribute , and by cycle through the list .attributes .
The code below shows the second method:
// Reference to our element var element = document.getElementById("universals"), attr; // Cycle over each attribute on the element for (var i = 0; i < element.attributes.length; i++) { // Store reference to current attr attr = element.attributes[i]; // If attribute nodeName starts with 'data-' if (/^data-/.test(attr.nodeName)) { // Log its name (minus the 'data-' part), and its value console.log( "Key: " + attr.nodeName.replace(/^data-/, ''), "Val: " + attr.nodeValue ); } } data-' part), and its value // Reference to our element var element = document.getElementById("universals"), attr; // Cycle over each attribute on the element for (var i = 0; i < element.attributes.length; i++) { // Store reference to current attr attr = element.attributes[i]; // If attribute nodeName starts with 'data-' if (/^data-/.test(attr.nodeName)) { // Log its name (minus the 'data-' part), and its value console.log( "Key: " + attr.nodeName.replace(/^data-/, ''), "Val: " + attr.nodeValue ); } } ^ data- /, ''), // Reference to our element var element = document.getElementById("universals"), attr; // Cycle over each attribute on the element for (var i = 0; i < element.attributes.length; i++) { // Store reference to current attr attr = element.attributes[i]; // If attribute nodeName starts with 'data-' if (/^data-/.test(attr.nodeName)) { // Log its name (minus the 'data-' part), and its value console.log( "Key: " + attr.nodeName.replace(/^data-/, ''), "Val: " + attr.nodeValue ); } }
Fiddle: http://jsfiddle.net/pGGqf/14/
You should find that this approach will work in all major browsers, even IE6. It optionally, again, in browsers that support element .dataset . The object .dataset have a bit more functionality, so you can detect them if you want to:
if (element.dataset) { // Browser supports dataset member } else { // Browser does not support dataset member }
source share