2

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"
        }
    ]
}

Desired result.

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! :)

5
  • 1
    Hi, so when learning a new language, it's often good to separate the full task into sub-tasks. for example - do you know how to create a loop in javascript? test doing that and just printing out something (eg the loop counter to console.log). Once you've got that working, then try looping through a hard-coded array and printing that to the console... then try looping through your JSON and printing that out... then figure out how instead of printing it to console, to insert it into an element on the page... then finally putting them in the correct page elements. You can do this :) Commented Dec 3, 2017 at 23:30
  • 1
    And you should learn JavaScript before you learn using Jquery. There is really no need to use jQuery for this. Commented Dec 3, 2017 at 23:33
  • @LucaKiebel, sometimes it is overkill to introduce a significantly large library to solve a simple problem. If you have a good knowledge of Javascript, you will have a better idea of when to use the one over the other. Having worked with many javascript developers, the ones who used jQuery the best were the ones who learned javascript first. They all had a better understanding of the issues that jQuery attempts to solve. Commented Dec 3, 2017 at 23:59
  • 1
    @LucaKiebel jQuery absolutely does not make things more efficient. Many functions are at least an order of magnitude slower, which certainly adds up. Your claim that vanilla JS is "pretty much obsolete when it comes to DOM manipulation" has no basis. It is trivial to do DOM manipulation, basically as easy as jQuery. Commented Dec 4, 2017 at 0:10
  • @LucaKiebel Until you take the time to fully learn the DOM API natively you'll be able to write code just as fast (if not faster) than you would with jQuery. As jhpratt mentioned, we've advanced with CSS transitions/animations, API fetching, and HTMLCollection conversion where it can be argued that jQuery is more the obsolete of the two. This is all without mentioning the overall performance benefit in avoid the library all together. Commented Dec 4, 2017 at 0:17

4 Answers 4

2

Let's pimp this out a bit.

We are going to use an HTML template and then decouple the structure as much as we can for the insert of data. We don't want to have to go digging around the javascript if we decide to change an h1 to an h2 for example.

I've also wrapped this in a list as what we have is a list of boxes. That is purely optional though.

/*GOing to hide the AJAX Call for the demo */
/*$.getJSON('content.json', function(data) {
  "use strict";

  var content = data.content;
*/

//Dummy Dump of our data;
var 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"
  }
];


//Set Up the template
var s = $("#boxTemplate")[0].innerHTML.trim();
var holder = document.createElement('div');
holder.innerHTML = s;
var boxTemplate = holder.childNodes

content.forEach(obj => {
  //Clone Template
  var newItem = $(boxTemplate).clone();
  //Populate it
  $(newItem).find(".head").html(obj['header']);
  $(newItem).find(".bodyContent").html(obj['para']);
  //Append it
  $("#boxes").append(newItem);
});

/*
What would be the closure of the Ajax call
});
*/
#boxes {
  list-style-type: none;
  padding: 0;
}

#boxes li {
  width: 33%;
  float: left;
  border: 1px solid black;
}

#boxes>li:nth-child(3n+1) {
  border-right: none;
}

#boxes>li:nth-child(3n+3) {
  border-left: none;
}

#boxes .head {
  border-bottom: 2px solid #999;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id="boxes">
</ul>
<!-- Ideally we'd use the new <template> tag here but IE support is no good -->
<script type="text/template" id="boxTemplate">
  <li>
    <h1 class="head"></h1>
    <p class="bodyContent">
  </li>
</script>

Sign up to request clarification or add additional context in comments.

Comments

1

What you want to use is a forEach loop, that way you don't have to care about how long your json-file's content array is:

$.getJSON('content.json', function (data) {

     "use strict";

     var content = data.content;
     content.forEach(e => {
        $("#"+e.id+" h1").html(e.header)
        $("#"+e.id+" p").html(e.para)
     });
});

Here is a working fiddle: https://jsfiddle.net/qsrehpa2/1/

Comments

1

You can loop through the content using the current object to fill in the elements as so:

$.getJSON('content.json', function(data) {
  "use strict";

  var content = data.content;

  content.forEach(obj => {
    $(`.box#${obj['id']}`)
      .find('h1').text(obj['header']).end()
      .find('p').text(obj['header']);
  });
});

Here's how a local copy would look without using json:

const 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"
  }
];

content.forEach(obj => {
  $(`.box#${obj['id']}`)
    .find('h1').text(obj['header']).end()
    .find('p').text(obj['para']);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<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>

Comments

1

You mentioned you want your solution to be scalable, so I wrote the jQuery code so that it automatically creates the HTML for you.

// Download the JSON file
$.getJSON("content.json", function (data) {
    // Loop through each JSON item
    $.each(data.content, function (index, item) {
        // Create and append HTML tags filled out with the data
        $("body").append(
             $("<div>")
                .attr("id", item.id)
                .append($("<h1>").text(item.header))
                .append($("<hr>"))
                .append($("<p>").text(item.para)));
     });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.