how can I add a div with a class of "tab" every 2 form-group I'm trying to create a step form but page builder is generating the html code. i want to see if I can do it with javascript i want the final result to be like this
<div >
<div ></div>
<div ></div>
</div>
<div >
<div ></div>
<div ></div>
</div>
<div >
<div ></div>
<div ></div>
</div>
<div >
<div ></div>
<div ></div>
</div>
<div >
<div ></div>
<div ></div>
</div>
CodePudding user response:
Hope I understood correctly. Html
<form id="my-form"> </form>
Script
let formElement = document.getElementById('my-form');
function generateTabs(times){
for(let i = 0; i< times i ){
generateTab();
}
}
function generateTab(){
let tabDiv = document.createElement('div');
tabDiv.className = 'tab'
let formGroupDiv = document.createElement('div');
formGroupDiv.className = 'form-group';
let secondformGroupDiv = document.createElement('div');
formGroupDiv.className = 'form-group';
tabDiv.appendChild(formGroupDiv);
tabDiv.appendChild(secondformGroupDiv);
formElement.appendChild(tabDiv);
}
CodePudding user response:
Yes this can be achieved through JS. Use createElement and appendChild in a loop.
const container = document.querySelector('.container');
const formGroups = document.querySelectorAll('.form-group');
for(let i = 0; i < formGroups.length; i = i 2){
const div = document.createElement('div');
div.className = 'tab';
div.appendChild(formGroups[i]);
div.appendChild(formGroups[i 1]);
container.appendChild(div);
}
.tab {
background: red;
margin-bottom: 3px;
display: flex;
flex-direction: column;
gap: 5px;
padding: 5px;
}
.form-group {
background: lightblue;
height: 10px;
}
<div >
<div ></div>
<div ></div>
<div ></div>
<div ></div>
<div ></div>
<div ></div>
<div ></div>
<div ></div>
<div ></div>
<div ></div>
</div>
CodePudding user response:
Looping through form
children:
const form = document.querySelector('form')
const copy = [...form.children]
let newHTML = ''
while (copy.length > 0) {
let tmp = document.createElement("div")
tmp.appendChild(copy.shift())
tmp.appendChild(copy.shift())
newHTML = '<div >' tmp.innerHTML '</div>'
}
form.innerHTML = newHTML
.tab {
border: 1px solid fuchsia;
}
<form>
<div >a</div>
<div >b</div>
<div >c</div>
<div >d</div>
<div >e</div>
<div >f</div>
<div >g</div>
<div >h</div>
<div >i</div>
<div >j</div>
</form>