admin管理员组文章数量:1246688
I want to create buttons and add classes to those button after creation I am working on below code !1 Please Help me out :)
Will this work?
$("#"+element.id).addClass(".btn");
Thank you in advance !!
for (var i = 0; i < 9; i++) {
add(i);
}
function add(i) {
var element = document.createElement("input");
element.type = "button";
element.value = i;
element.name = i + 1;
element.id = "btn" + i;
element.onclick = function() {
window.move(i);
};
var append = document.getElementById("append");
append.appendChild(element);
alert(element.id);
$("#" + element.id).addClass(".btn");
}
I want to create buttons and add classes to those button after creation I am working on below code !1 Please Help me out :)
Will this work?
$("#"+element.id).addClass(".btn");
Thank you in advance !!
for (var i = 0; i < 9; i++) {
add(i);
}
function add(i) {
var element = document.createElement("input");
element.type = "button";
element.value = i;
element.name = i + 1;
element.id = "btn" + i;
element.onclick = function() {
window.move(i);
};
var append = document.getElementById("append");
append.appendChild(element);
alert(element.id);
$("#" + element.id).addClass(".btn");
}
Share
Improve this question
edited Nov 22, 2017 at 8:34
empiric
7,8787 gold badges38 silver badges49 bronze badges
asked Nov 22, 2017 at 8:32
Vaisakh MAVaisakh MA
1041 gold badge1 silver badge11 bronze badges
2
- Possible duplicate of How do I add a class to a given element? – Sean Commented Nov 22, 2017 at 8:35
-
when using
.addClass()
you can omit the.
in front of the classname – empiric Commented Nov 22, 2017 at 8:35
5 Answers
Reset to default 4You can add classes in javascript like that:
element.className += 'className';
If you are using jQuery then what you did is correct, except the dot you put into addClass function. So instead of:
$(element).addClass('.className');
You do:
$(element).addClass('className');
You can add class directly by accessing "className" property.
var element = document.createElement("input");
element.type = "button";
element.className = "clr-red";
Refer here for more
I think you should use without dot.
$("#"+element.id).addClass("btn");
You can just use the classList.add method on the element you create.
for (var i = 0; i < 9; i++)
{
add(i);
}
function add(i) {
var element = document.createElement("input");
element.type = "button";
element.value = i;
element.name = i + 1;
element.id="btn"+i;
element.classList.add("btn");
element.onclick = function () {
window.move(i);
};
var append =document.getElementById("append");
append.appendChild(element);
}
you just type the class name only
addClass("btn"); instead of addClass(".btn");
本文标签: javascriptAdd class to button inside a js functionStack Overflow
版权声明:本文标题:javascript - Add class to button inside a js function - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1740261610a2250380.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论