Home > Back-end >  How to append div multiple times using JavaScript
How to append div multiple times using JavaScript

Time:10-24

I want to append the HTML child_element div multiple times as defined on variables inside the parent_element using Javascript.

Desire Output:

<div class="parent_element">
   <div class = "child_element">
   <div class = "child_element">
   <div class = "child_element">
   <div class = "child_element">
   <div class = "child_element">
</div>

Please Help !!!

CodePudding user response:

You can create a child node object and append it to the parent node in loop. Since you have multiple child nodes to be appended you can use DocumentFragment

const parentNode = document.createElement('div');
parentNode.classList.add('parent_element');
const childNode = document.createElement('div');
childNode.classList.add('child_element');
const fragment = new DocumentFragment();

for(let i=0; i<[*no_of_times_you_want_child_node*]; i  ) {
    fragment.appendChild(childNode.cloneNode(true));
}

// finally append dom fragment to parent
parentNode.appendChild(fragment);

CodePudding user response:

Assuming that you want the number of children to be defined by an attribute "variables inside the parent_element"

<div class="parent" children="5"></div>
<script>
const parentEl = document.querySelector(".parent");
const numOfChildren =  parentEl.getAttribute("children");
const fragment = new DocumentFragment();
for (let i=0; i<numOfChildren; i  ) {
    const childEl = document.createElement("div");
    childEl.classList.add("child");
    fragment.appendChild(childEl);
}
parentEl.append(fragment);
</script>

The basic process is:

  1. Get a reference to the parent element using the class selector
  2. Retrieve the number of children you want from the attribute named children. This is a string value so the will convert it to a number
  3. Loop through the creation of a new element on the DOM adding the desired class name before appending the child.

Edit: As per pilchard's suggestion I've merged in DocumentFragment from abhishek khandait's answer.

CodePudding user response:

You can dynamically add a new div element using jquery.

   <script> 
        function addNewDivElement() {
            $("#parent_element").append('<div class = "child_element">')
        }
    </script> 

the function addNewDivElement can be called on click of a button. something like below:

  <button onclick="addNewDivElement()"> 
        Add
  </button> 

  • Related