Neek
Neek

Reputation: 13

Create element in another div element using classname

I'm trying to create new elements in another pre-existing <div> element using js DOM. I'm able to do this if that <div> is called using id but I want to accomplish this by class

This is what I have so far

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

Upvotes: 0

Views: 86

Answers (2)

jpcanamaque
jpcanamaque

Reputation: 1069

You could also do this by using 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');
    });
});

You can replace $('<div>A</div>') part with whatever element you want to append in your <div>

Fiddle here

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

getElementsByClassName() returns a HTMLCollection which is an array like collection of object, which does not have the appendChild() method. You need to get the first element form the list using an index based lookup then call the 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>

Upvotes: 2

Related Questions