Search code examples
javascripthtmlappendchild

How to place random elements in a HTML document using Javascript?


I´m developing a Javascript game and I have to place random coins in the HTML document. I have used this code so far:

 createCoin() {
    section=document.createElement("div");
    section.innerHTML='<img src="./img/coin.png"/>';
    document.body.appendChild(section);
 }

This code simply places an image coin in the coordinates (0,0) of the document. What I want to do is access that recently created "div" and give it a random coordinate that I generate in another function so if I call several times the createCoin it creates several coins in the document. I can't use jQuery. Any ideas?


Solution

  • Have createCoin return the div and then use it.

    createCoin() {
        section=document.createElement("div");
        section.innerHTML='<img src="./img/coin.png"/>';
        document.body.appendChild(section);
    
        section.style.position = 'absolute';
        section.style.left = '0px'; // units ('px')  are unnecessary for 0 but added for clarification
        section.style.top = '0px';
    
        return section;
     }
    

    e.g.: var coin = createCoin(); coin.style.left = ???; coin.style.top = ???;