这个w3schools页面提到了HTML DOM createElement()方法。例如,您可以通过以下方式创建按钮
var btn = document.createElement(“ BUTTON”);
但是,如何向该按钮添加ID /类别?我还能用它做什么?
使用Javascript的一种方法是使用setAttribute:
element.setAttribute(name, value);
例:
var btn=document.createElement("BUTTON");
btn.setAttribute("id", "btn_id");
btn.setAttribute("class", "btn_class");
btn.setAttribute("width", "250px");
btn.setAttribute("data-comma-delimited-array", "one,two,three,four");
btn.setAttribute("anything-random", document.getElementsByTagName("img").length);
这种方式的优点是您可以将任意值分配给任意名称。https://developer.mozilla.org/zh-CN/docs/Web/API/element.setAttribute
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句