Adding data attribute to DOM

Luntegg picture Luntegg · Feb 18, 2013 · Viewed 253.8k times · Source
$('div').data('info', 1);

alert($('div').data('info'));
//this works    

$('div[data-info="1"]').text('222');
//but this don't work

I'm creating element within jquery. After that, I want to add attribute "data". He's like and is added, but in the DOM, this is not apparent, and I can't get the item, using

$('div[data-example="example"]').html()

jsfiddle

Answer

Blender picture Blender · Feb 18, 2013

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');