我正在尝试使用JS DOM在另一个预先存在的<div>元素中创建新元素。
如果使用<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/

10-12 12:41
查看更多