I want to create a JS loop (using jQuery) that looks through the JSON file and adds the appropriate content to the HTML file, based on whether the <div> ids match the JSON "id" values. This needs to be easily scalable and work regardless of how many <div> boxes are added.
I have a HTML file set up as follows:
<div class="box" id="1">
<h1></h1>
<hr/>
<p></p>
</div>
<div class="box" id="2">
<h1></h1>
<hr/>
<p></p>
</div>
<div class="box" id="3">
<h1></h1>
<hr/>
<p></p>
</div>
And a seperate JSON file with the values for each box element:
{
"content": [
{
"id": 1,
"header": "Box 1",
"para": "This is Box 1",
"other": "Another key that's not necessarily used for all boxes"
},
{
"id": 2,
"header": "Box 2",
"para": "This is Box 2"
},
{
"id": 3,
"header": "Box 3",
"para": "This is Box 3",
"other": "Another key that's not necessarily used for all boxes"
}
]
}
Essentially this is the result I'm looking for (with some basic CSS styling added), created using the following script, though obviously this code would have to be changed each time a new <div> is added, so isn't scalable:
$.getJSON('content.json', function (data) {
"use strict";
var content = data.content;
$('#1 h1').html(content[0].header);
$('#2 h1').html(content[1].header);
$('#3 h1').html(content[2].header);
$('#1 p').html(content[0].para);
$('#2 p').html(content[1].para);
$('#3 p').html(content[2].para);
});
Detailed answers would be appreciated, as I'm still fairly new to JS and JSON and haven't found any that exactly explain what I'm trying to achieve.
Thanks! :)
