我正在尝试在另一个预先存在的 <div>
中创建新元素使用 js DOM 的元素。
如果<div>
我能够做到这一点使用 id
调用但我想通过 class
来完成此任务
这就是我目前所拥有的
<html>
<body>
<button onclick="whiskey()">go</button>
<div class="pagination-pagination-right">
<!-- I want to spawn new Elements here !-->
</div>
<div class="controlElement">
<p> This is just a control Element</p>
</div>
<script type="text/javascript">
function whiskey(){
var input=document.createElement("input");
input.type="text";a
input.id="sad";
var newdiv=document.createElement("div");
newdiv.appendChild(input);
/* this part doesn't work */
var maindiv=document.getElementsByClassName("pagination-pagination-right");
maindiv.appendChild(newdiv);
}
</script>
</body>
</html>
最佳答案
getElementsByClassName()返回 HTMLCollection这是一个类似数组的对象集合,它没有 appendChild()
方法。您需要使用基于索引的查找从列表中获取第一个元素,然后调用 appendChild()
function whiskey() {
var input = document.createElement("input");
input.type = "text";
//ID of an element must be unique
input.id = "sad";
var newdiv = document.createElement("div");
newdiv.appendChild(input);
var maindiv = document.getElementsByClassName("pagination-pagination-right");
maindiv[0].appendChild(newdiv);
}
<button onclick="whiskey()">go</button>
<div class="pagination-pagination-right">
<!-- I want to spawn new Elements here !-->
</div>
<div class="controlElement">
<p>This is just a control Element</p>
</div>
关于javascript - 使用类名在另一个 div 元素中创建元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26378346/