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");
Question
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");
OTHER TIPS
use:
btn.className = btn.className + "test";
$(btn).css('font-weight','bold') or $(btn).addClass('className');
all is OK.
with jQuery:
$(btn).addClass('your-class');
(see jQuery docs)
without jQuery:
btn.className = 'your-class';
Try btn.className
after createElement
var btn=document.createElement('BUTTON');
btn.className = "CLASS_NAME";
var t=document.createTextNode("X");
btn.appendChild(t);
x.appendChild(btn);