Search code examples
javascriptjqueryhtmljquery-data

How to set data attribute with jQuery on element that is not in DOM yet?


How can I set the data-attribute with jQuery on an element that is not in the DOM yet?

Code:

   var panelHeading = $('<div/>', {class:'panel-heading', href:'#'+username+'PanelContent'});
   panelHeading.data('toggle', 'collapse').data('target',"#"+username+"PanelContent");

The data attributes don't appear when I append it to the document. The other attributes do appear.


Solution

  • You can add data attributes when creating the element

    var panelHeading = $('<div />', {
        'class'       : 'panel-heading', 
        href          : '#'+username+'PanelContent',
        'data-toggle' : 'collapse',
        'data-target' : '#'+username+'PanelContent'
    });
    

    using data() stores the data internally in jQuery, it does not create HTML attributes, so it works rather poorly with attributes for things like Bootstrap