Search code examples
phpjavascriptdynamicdynamically-generated

Dynamically Generate divs with different ids with PHP


I want to generate a certain number of divs using PHP with different ids, I know how to generate them for a set number, but how do I generate on click, with different ids? Also, if I wanted to delete a div (and its corresponding id) how would I do that?

This is the code I have for generating (6) divs

 $element = "<div></div>";
    $count = 6;
    foreach( range(1,$count) as $item){
        echo $element;
    }

I need something like the click() in jquery/javscript (but in PHP) to trigger div creation instead and I don't even know where to start.


Solution

  • In JavaScript you can do

    function createDiv(id, parent)
    {
        var elem = document.createElement('div');
        elem.id = id;
        document.getElementById(parent).appendChild(elem);
    }
    
    createDiv(10, id-of-parent-elem-to-append-to);
    

    where 10 will be the ID of the new element and you will have to supply the ID of the element to which the new DIV should be appended, as the 2nd argument