Using JS to add div elements dynamically – User friendly Tech help
Scenario:- Legacy code thrown at you with new UX design, and you cannot touch the original code. So doing latest UI changes is headache.
n
Solution:- Play with the structure of the html and add latest flexbox or grid CSS to make your life hell easier.
n
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.
n
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)
n
// function to get form elments by ID/Classnfunction getElement(type,name) {n if(type ==='ID'){n return document.getElementById(name);n }else{n return document.getElementsByClassName(name);n }n}nn// function doing the restructuring nfunction reFormMe() {n const ID = 'ID',n CLASS_NAME = 'CLASS';n // Getting the values of existing div'sn getElement('ID','FirstName').value = "";n getElement('ID','LastName').value = "";n getElement('ID','Company').value = "";n getElement('ID','Email').value = "";n // change email/phone field widthn getElement('ID','Email').style.width= "420px";n getElement('ID','Phone').style.width= "268px";n // adding the extra div to add CSS displayflex propertyn // get the parent div, assuming it have IDn const oldParent = getElement('ID','oldForm'),n // get elements with the same class into a arrayn arrElements = getElement('CLASS','rows'),n firstName = arrElements[0],n lastName = arrElements[1],n email = arrMarkarrElementseto[2],n company = arrElements[3],n // incase form is already restructed, don't do it (check that new css class is applied or not)n if(!getElement('CLASS','row-upgrade').length){n // first/last name - create div at run time and add this as parentn const row1 = document.createElement('div');n row1.className = 'row-upgrade row1';n oldParent.appendChild(row1);n row1.appendChild(firstName);n row1.appendChild(lastName);n // Titemaille/Companyn const row2 = document.createElement('div');n row2.className = 'row-upgrade row2';n oldParent.appendChild(row2);n row2.appendChild(email);n row2.appendChild(company);n }nn }n// calling the re-struturing function which is doing the magicn window.onload = reFormMe();n
n
Before
n
n
After
n