javascript – Attribute 'data- *' html – Creation rules

Question:

Can you create the data attributes followed by a number, data-0 = "mexico" ?

Or something like this:

data-data1 = "mexico" 

The idea is to retrieve them through an iteration and thus avoid writing attribute by attribute.

Answer:

It is not necessary to use numbering to iterate over them, nor is it necessary to iterate attribute by attribute using their names. Recent versions of jQuery (if you're trying to do it using jQuery) allow you to get all the data-* attributes by simply calling the data() method without parameters:

 $(document).ready(function() { var atributos = $("#prueba").data(); console.log(atributos); // Uno de ellos console.log(atributos.pais); // Para iterar sobre los atributos $.each(atributos, function(key, elem) { console.log(key + ' -> ' + elem); }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h1 id="prueba" data-id="1" data-ciudad="Lima" data-pais="Peru"> Prueba </h1>

With JavaScript you can use the element's dataset attribute:

document.addEventListener("DOMContentLoaded", function(event) { 
    var element = document.getElementById("prueba");
    var data = element.dataset;
    console.log(data);
 
    // Para iterar sobre los atributos
    for (key in data) {
        console.log(key + ' -> ' + data[key]);
    }
});
<h1 id="prueba" data-id="1" data-ciudad="Lima" data-pais="Peru">
    Prueba
</h1>
Scroll to Top