使用classname在另一个div元素中创建元素

时间:2014-10-15 08:54:04

标签: javascript html

我尝试使用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>

2 个答案:

答案 0 :(得分:2)

getElementsByClassName()返回一个HTMLCollection,它是一个类似于object集合的数组,它没有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>

答案 1 :(得分:0)

你也可以使用jQuery

来做到这一点

<强> HTML

   <button>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>

<强>的jQuery

$(function(){
    $('button').click(function(){
        $('<div>A</div>').appendTo('.pagination-pagination-right');
    });
});

您可以将$('<div>A</div>')部分替换为您想要添加到<div>

中的任何元素

小提琴here