How to set data attribute in JQuery
By FoxLearn 12/11/2024 1:34:42 AM 89
The .data()
method in jQuery is used to set or get values associated with data attributes in a more JavaScript-friendly way.
For example, Using .data()
Method
$('#element').data('key', 'value');
Here, 'key'
is the name of the data attribute (without the data-
prefix), and 'value'
is the value you want to assign to that attribute.
html
<div id="myDiv"></div>
js
$('#myDiv').data('color', 'blue'); // Setting data-color="blue"
When using .data()
, it automatically handles retrieving and updating values in a cache, but it won't update the actual HTML attribute (i.e., the data-*
attribute) in the DOM until you explicitly call .attr()
.
How to set data attributes in HTML elements?
For example, Using .attr()
to Set the data-*
Attribute
If you want to set the actual data-*
attribute in the DOM, use the .attr()
method.
$('#element').attr('data-key', 'value');
For example:
html
<div id="mydiv" data-myval="15"></div>
js
var a = $('#mydiv').data('myval'); //getter $('#mydiv').data('myval',20); //setter
jQuery uses the .data()
method to store internal information under the names events
and handle
, and it also reserves any data attribute starting with an underscore (_
) for internal purposes.
jQuery's .data()
method does not modify the data-*
attribute in the HTML. If you need to update the data-*
attribute directly in the HTML, you should use the .attr()
method instead.
html
<div id="outer"> <div id="mydiv" data-myval="15"></div> </div>
jQuery
alert($('#outer').html()); // alerts <div id="mydiv" data-myval="15"> </div> var a = $('#mydiv').data('myval'); //getter $('#mydiv').attr("data-myval","20"); //setter alert($('#outer').html()); //alerts <div id="mydiv" data-myval="20"> </div>
Use .data('key', value)
to set internal data for jQuery, which doesn’t directly modify the HTML.
Use .attr('data-key', value)
to set the actual data-*
attribute in the HTML.