Reputation: 507
I am creating dynamic buttons using jQuery, is there a way to add CSS class to it while creating it, what I want to avoid is to write another line of JavaScript to add CSS class to it, unless there is no other way. Find the code snippet below,
$.each(data, function (index, value) {
var button = $('<button/>', {
text: value,
id: 'btn_' + index,
click: function () { MNS.ButtonClick(this) }
});
$('#MyDiv').append(button);
});
do we have something like this,
$.each(data, function (index, value) {
var button = $('<button/>', {
text: value,
id: 'btn_' + index,
**css:'Myclass'**
click: function () { MNS.ButtonClick(this) }
});
$('#MyDiv').append(button);
});
Upvotes: 1
Views: 2239
Reputation: 6031
use below code . use class
as parameter.
var button = $('<button/>', {
class : "className",
click: function () { MNS.ButtonClick(this) }
});
Upvotes: 2
Reputation: 133433
You can set class
in constructor
$.each(data, function (index, value) {
var button = $('<button/>', {
"class" : "myClass" //Set the CSS to be add
});
});
OR, use the method addClass
on created object
button.addClass('myClass')
Upvotes: 5