How to repeat div element n times in HTML?

前端 未结 5 1120
时光说笑
时光说笑 2020-12-09 21:44

How can I duplicate a

so there are n copies using JavaScript?

Start with 1:

相关标签:
5条回答
  • 2020-12-09 22:20

    Using the pure JS node.cloneNode:

    https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode

    function multiplyNode(node, count, deep) {
        for (var i = 0, copy; i < count - 1; i++) {
            copy = node.cloneNode(deep);
            node.parentNode.insertBefore(copy, node);
        }
    }
    
    multiplyNode(document.querySelector('.box'), 5, true);
    

    Pass true as third argument to multiplyNode to copy child nodes too.

    Here's a demo.

    Edit:

    With ES6 condensed syntax, the above example becomes:

    const node = document.querySelector('.box');
    [...Array(5)].forEach(_ => node.parentNode.insertBefore(node.cloneNode(true), node));
    
    0 讨论(0)
  • 2020-12-09 22:31

    im using jquery here. You can place div parent as i used in example "divRepeat"

    <div id="divRepeat">
       <div class="box"></div>
    </div>
    

    in Jquery

    for(var i=0;i<("how many repeat do you want");i++){
       $("#divRepeat").append($(".box").html());
       //you can add other logic here, like you want diferent id or class to add in new box
    }
    
    0 讨论(0)
  • 2020-12-09 22:31

    Make use of php with apache server, change the extension from .html to .php and use:

    <?php
    
    for ($i = 1; $i <= 10; $i++) {
        echo "<div id='box'></div>";
    }
    
    ?>
    
    0 讨论(0)
  • 2020-12-09 22:41

    Create a container div with a id and place <div class="box"></div> inside it. Then using jQuery you can run a loop for desired number of time and append divs like

    jQuery("#container_div_id").append(jQuery("#container_div_id").children().first().clone())
    

    Check fiddle

    0 讨论(0)
  • 2020-12-09 22:43

    Take a look at the fiddle to get your result

    https://jsfiddle.net/dcpg4v1c/

    $(document).ready(function(){
       for(var i = 0; i< 5; i++)
         $("#dvMain").append("<div class='row'>Test</div>");  
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id='dvMain'></div>

    0 讨论(0)
提交回复
热议问题