1

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);
  });
1
  • 2
    "class" : "myClass" Commented Oct 19, 2015 at 12:58

2 Answers 2

5

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')
Sign up to request clarification or add additional context in comments.

Comments

2

use below code . use class as parameter.

var button =  $('<button/>', {
        class : "className",
        click: function () { MNS.ButtonClick(this) }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.