Using JS to add div elements dynamically

js adding div at runtime

Scenario:- Legacy code thrown at you with new UX design, and you cannot touch the original code. So doing latest UI changes is headache.

Solution:- Play with the structure of the html and add latest flexbox or grid CSS to make your life hell easier.

How i did re-structuring was appending new parent div, which can be set as “display:flex” so child div’s can be aligned easily.

Sample code, from this you can get an idea how new parent is added with its own CSS class.(which can be used to redesign the UI)

// function to get form elments by ID/Class
function getElement(type,name) {
    if(type ==='ID'){
        return  document.getElementById(name);
        return  document.getElementsByClassName(name);

// function doing the restructuring 
function reFormMe() {
        const ID = 'ID',
        CLASS_NAME = 'CLASS';
        // Getting the values of existing div's
        getElement('ID','FirstName').value = "<?php echo $firstName ?>";
        getElement('ID','LastName').value = "<?php echo $lastName ?>";
        getElement('ID','Company').value = "<?php echo $company ?>";
        getElement('ID','Email').value = "<?php echo $email ?>";
        // change email/phone field width
        getElement('ID','Email').style.width= "420px";
        getElement('ID','Phone').style.width= "268px";
        // adding the extra div to add CSS displayflex property
        // get the parent div, assuming it have ID
        const oldParent = getElement('ID','oldForm'),
        // get elements with the same class into a array
        arrElements = getElement('CLASS','rows'),
        firstName = arrElements[0],
        lastName = arrElements[1],
        email = arrMarkarrElementseto[2],
        company = arrElements[3],
        // incase form is already restructed, don't do it (check that new css class is applied or not)
            // first/last name - create div at run time and add this as parent
            const row1 = document.createElement('div');
            row1.className = 'row-upgrade row1';
            // Titemaille/Company
            const row2 = document.createElement('div');
            row2.className = 'row-upgrade row2';

// calling the re-struturing function which is doing the magic
 window.onload = reFormMe();


js adding div at runtime




Leave a Reply

Your email address will not be published. Required fields are marked *