• notice
  • Congratulations on the launch of the Sought Tech site

Use JS or jQuery to read and write the data-* attributes of HTML elements


HTML5 has added data-*attributes.
Insert picture description here
In some front-end frameworks Bootstrap, you can also see data-*the application of
attributes: Sorting and summary of data-* attributes in Bootstrap

  • jQuery: $(selector).data(name)get

  • JS: The document.getElementById(selector).datasetreturn value is DOMStringMapan object of type.
    $(selector)[0].dataset. ( jQuery Object [0]Available DOM Object)

Use jQuery to read and write data-* attributes

  • jQuery API
    data(key, value)

  • Code
    <head>introduce jQuery dependency (CDN or local dependency)
    <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
    in <body>Code: Then, test the code in:

    <p id="p1" data-name="123">Use jQuery to read and write data-* attributes</p>
        console.log($("#p1").data("name")); // Read the attribute value of data-name (remove the data- prefix)
        $("#p1").data("name", "abc"); // Update the value of the data-name attribute (remove the data- prefix)
        console.log($("#p1").data("name")); // read again

    Visit the page in the browser and view the console output as follows:


Use JS to read and write data-* attributes

  • Code
    <bode>test the code in:

    <p id="p2" data-name="张三">Use JS to read and write data-* attributes</p>
        var pObj = document.getElementById("p2"); // Get DOM element
        console.log(pObj.dataset.name); // Read (dataset attribute of DOM element)
        pObj.dataset.name = "Li Si"; // write
        console.log(pObj.dataset.name); // read again

    The console output is as follows:

    Zhang San Li Si
  • The Web API
    DOM element.dataset is the DOMStringMaptype, and this object contains the data-*mapping relationship between the attribute name (not including the data-prefix) and the value.

Test code:

<p id="p3" data-id="1001", data-name="张三", data-gender="M">Test DOMStringMap</p>
    var p = document.getElementById("p3"); // Get DOM element
    var pMap = p.dataset; // Get DOMStringMap object

Check the console output: In
Insert picture description here
other words, we can customize multiple data-*attributes to HTML tags , and then use DOM element.datasetthis attribute to get the DOMStringMapformatted object,
this object contains 
data-*the name:value pair of our custom attribute (the name is automatically removed from the prefix data-).


Technical otaku

Sought technology together

Related Topic


Leave a Reply