JSFiddle - React, Tailwind, and code Playground

by marsone

HTML

<body onload="addElement()">
    <div id='org_div1'>The text above has been created dynamically.</div>
</body>

JavaScript

var my_div = null;
var newDiv = null;

function addElement() {
    for (var i = 1; i <= 10; i++) {
        var newDiv = document.createElement("div");
        var newContent = document.createTextNode("I am div no " + i);

        newDiv.appendChild(newContent); //add the text node to the newly created div.
        newDiv.id = "div" + i;

        // add the newly created element and its content into the DOM
        my_div = document.getElementById("org_div1");
        document.body.insertBefore(newDiv, my_div);
    }
    bgcolor();
    txcolor();
}

function bgcolor() {
    for (var i = 1; i <= 10; i++) {
        var color = "rgb(" + Math.floor((Math.random() * 255)) + "," + Math.floor((Math.random() * 255) ) + "," + Math.floor((Math.random() * 255) ) + ")";
        var txcolor = "rgb(" + Math.floor((Math.random() * 255)) + "," + Math.floor((Math.random() * 255) ) + "," + Math.floor((Math.random() * 255) ) + ")";
        var element = document.getElementById("div" + i);
        element.setAttribute("style", "width: 500px; background-color:" + color + ";");
        element.style.color = txcolor;
    }
}