I'm facing a small issue in adding data div through JSON. I want that in the main div I can show the Role name and inside that all the branches details one by one. Anyhow, I crack some of the parts but somewhere my code is cracking up. Please help me to create this in a proper manner. My HTML looks like this:
In UI/UX it is taking the branch name of Jenkins too. Don't know where I'm going wrong. And even the last data is not coming.
JSFiddle Link is : https://jsfiddle.net/abhishek_kumar_13092/abLf93t8/139/.
var div = document.createElement('div');
div.id = "mainContainer";
div.className = "mainContainer";
var innerDiv = document.createElement('div');
innerDiv.id = "innerContainer";
innerDiv.className = "innerContainer"
JSONData.forEach(function(data, index) {
div.innerHTML = '<div id=' data.name ' >' '<p >' data.name '</p>' '</div>';
document.getElementById("container").appendChild(div);
data.branches.forEach((branch)=>{
innerDiv.innerHTML = '<p id=' branch.name ' >' branch.name '</p>'
document.getElementById(data.name).appendChild(innerDiv);
})
})
CodePudding user response:
You need to initialize the innerDiv
in each loop again
var JSONData = [{
"name": "Jenkins",
"location": "Pune",
"role": "Testing",
"branches": [{
"name": "Jenkins_pune1",
"location": "Pune_Hin",
"role": "Testing_Automation",
"id": "PUN_HINJE_T122"
}, {
"name": "Jenkins_pune2",
"location": "Pune_DC",
"role": "Testing_UI",
"id": "PUN_DC_TDC121"
}]
}, {
"name": "UI/UX",
"location": "Delhi",
"role": "UI_Dev",
"branches": [{
"name": "UIUX_Del1",
"location": "Del_Sec1",
"role": "UI",
"id": "Del_Sec1_T122"
}, {
"name": "UIUX_Del2",
"location": "Del_Sec3",
"role": "Testing_UI",
"id": "Del_Sec3_TDC121"
}]
}, {
"name": "Back-End",
"location": "Mumbai",
"role": "Dev",
"branches": [{
"name": "Dev_Mum1",
"location": "Mum_Sec1",
"role": "Dev",
"id": "Mum_Sec1_Dv122"
}, {
"name": "Dev_Mum2",
"location": "Mum_Sec3",
"role": "Dev",
"id": "Mum_Sec3_Dev21"
}]
}]
var div = document.createElement('div');
div.id = "mainContainer";
div.className = "mainContainer";
JSONData.forEach(function(data, index) {
div.innerHTML = '<div id=' data.name ' >' '<p >' data.name '</p>' '</div>';
document.getElementById("container").appendChild(div);
var innerDiv = document.createElement('div');
innerDiv.id = "innerContainer";
innerDiv.className = "innerContainer"
data.branches.forEach((branch)=>{
innerDiv.innerHTML = '<p id=' branch.name ' >' branch.name '</p>'
document.getElementById(data.name).appendChild(innerDiv);
})
})
.unitName {
box-shadow: rgba(0, 0, 0, 0.15) 1.95px 1.95px 2.6px;
padding: 5px;
margin: auto;
}
#mainContainer {
width: 80%;
padding: 5px;
margin: 5px auto 5px;
background: whitesmoke;
align-items: center;
}
.roleName {
background: crimson;
width: 80%;
text-align: center;
font-weight: 600;
color: white;
}
<div id="container"></div>