In order to create a new data attribute in JavaScript we just need to add a new property to the dataset object with a value. This will update the dataset object and our HTML which means our HTML will look like this.
The data-* attribute consist of two parts: The attribute name should not contain any uppercase letters, and must be at least one character long after the prefix "data-" The attribute value can be any string.
Adding a data attribute is easy. Any HTML element can have any number of data attributes added to its opening tag. We simply type data- followed by the name of our attribute into the element's opening tag alongside any other attributes we're already using.
Use the .data()
method:
$('div').data('info', '222');
Note that this doesn't create an actual data-info
attribute. If you need to create the attribute, use .attr()
:
$('div').attr('data-info', '222');
jQuery's .data() does a couple things but it doesn't add the data to the DOM as an attribute. When using it to grab a data attribute, the first thing it does is create a jQuery data object and sets the object's value to the data attribute. After that, it's essentially decoupled from the data attribute.
Example:
<div data-foo="bar"></div>
If you grabbed the value of the attribute using .data('foo')
, it would return "bar" as you would expect. If you then change the attribute using .attr('data-foo', 'blah')
and then later use .data('foo')
to grab the value, it would return "bar" even though the DOM says data-foo="blah"
. If you use .data()
to set the value, it'll change the value in the jQuery object but not in the DOM.
Basically, .data()
is for setting or checking the jQuery object's data value. If you are checking it and it doesn't already have one, it creates the value based on the data attribute that is in the DOM. .attr()
is for setting or checking the DOM element's attribute value and will not touch the jQuery data value. If you need them both to change you should use both .data()
and .attr()
. Otherwise, stick with one or the other.
in Jquery "data" doesn't refresh by default :
alert($('#outer').html());
var a = $('#mydiv').data('myval'); //getter
$('#mydiv').data("myval","20"); //setter
alert($('#outer').html());
You'd use "attr" instead for live update:
alert($('#outer').html());
var a = $('#mydiv').data('myval'); //getter
$('#mydiv').attr("data-myval","20"); //setter
alert($('#outer').html());
$(document.createElement("img")).attr({
src: 'https://graph.facebook.com/'+friend.id+'/picture',
title: friend.name ,
'data-friend-id':friend.id,
'data-friend-name':friend.name
}).appendTo(divContainer);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With