jqueryhtmlcustom-data-attribute

Adding data attribute to DOM


$('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


Solution

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

    Remember, this is just a data-* attribute, so the value has to be a string.