简体   繁体   中英

How to append div multiple times using JavaScript

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

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

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 beforeappending the child .

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

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM