Use JS or jQuery to read and write the data-* attributes of HTML elements
Intro
HTML5 has added data-*
attributes.
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)
getJS: The
document.getElementById(selector).dataset
return value isDOMStringMap
an object of type.
Or$(selector)[0].dataset
. (jQuery Object [0]
AvailableDOM 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
DOMStringMapDOM element.dataset
is theDOMStringMap
type, and this object contains thedata-*
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
other words, we can customize multiple data-*
attributes to HTML tags , and then use DOM element.dataset
this attribute to get the DOMStringMap
formatted object,
this object contains data-*
the name:value pair of our custom attribute (the name is automatically removed from the prefix data-
).
0 Comments