Search code examples
elementnew-operator

How to add child element with class ? through JS


I have an element with the following id="loader-wrap"

<div id="loader-wrap"></div>

I want to add a new div element btw the above parent div automatically including add class "Pin" where ever I have this Id element.

Want this: <div id="loader-wrap"><div class="Pin"></div></div>


Solution

  • Use document.createElement() method:

    var pin = document.createElement("div"); // create new div
    pin.setAttribute("class", "Pin"); // set class to the div
    
    var loaderWrap = document.getElementById("loader-wrap"); // get the parent element
    loaderWrap.appendChild(pin); // append the new div to the parent