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 = $('', {class:'panel-heading', href:'#'+username+
Solution 1:
jQuery's data()
method doesn't set HTML5 data-
attributes, it actually stores high-level data in the DOM element. You can store complex objects and functions using data()
that you can't using attributes.
If you really must set an attribute, use attr('data-toggle','collapse')
and the like. But as mentioned in an earlier comment, why not just set it in the initial declaration?
Solution 2:
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
Solution 3:
You can use:
var panelHeading = $('<div data-target="' + '#'
+ username + 'PanelContent' + '"/>');
Post a Comment for "How To Set Data Attribute With Jquery On Element That Is Not In Dom Yet?"