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

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

Intro

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.
    Or 
    $(selector)[0].dataset. ( jQuery Object [0]Available DOM Object)

Use jQuery to read and write data-* attributes

  • jQuery API
    data(key, value)
    data(obj)

  • Code
    First, 
    <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>
    <script>
        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
    </script>

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

    123abc

Use JS to read and write data-* attributes

  • Code
    directly 
    <bode>test the code in:

    <p id="p2" data-name="张三">Use JS to read and write data-* attributes</p>
    <script>
        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
    </script>

    The console output is as follows:

    Zhang San Li Si
  • The Web API
    DOMStringMap
    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>
<script>
    var p = document.getElementById("p3"); // Get DOM element
    var pMap = p.dataset; // Get DOMStringMap object
    console.log(pMap);
</script>

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-).


Tags

Technical otaku

Sought technology together

Related Topic

0 Comments

Leave a Reply

+