How to set data attribute in JQuery
By FoxLearn Published on Dec 11, 2024 494
JQuery set data attribute
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 to add a data attribute to an element using jQuery.
// jquery add data attribute to element $('#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.
For example, html data attribute jquery
<div id="myDiv"></div>
For example, js set data attribute
$('#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 with the HTML data attribute jQuery.
$('#element').attr('data-key', 'value');
For example, html data attribute jquery
<div id="mydiv" data-myval="15"></div>
For example, jquery access data attribute
// javascript get data attribute var a = $('#mydiv').data('myval'); //getter // javascript set data attribute $('#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.
For example, html template
<div id="outer"> <div id="mydiv" data-myval="15"></div> </div>
For example, change data value jquery
alert($('#outer').html()); // alerts <div id="mydiv" data-myval="15"> </div> var a = $('#mydiv').data('myval'); //getter // jquery update data attribute, add attr jquery $('#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.