Search code examples
javascriptjqueryappendchild

how to add class to button by using appendChild?


i have created a button like this

var btn=document.createElement('BUTTON');
var t=document.createTextNode("X");
btn.appendChild(t);
x.appendChild(btn);

how can i add class to this button?


Solution

  • Not by using .appendChild(), but rather by setting the .className property on the created element itself:

    btn.className = "myclass";
    

    Or if you don't care about older browsers, you can use .classList:

    btn.classList.add("myClass");