1

The problem I am having with this exercise is I need to output on my html a list <li></li> and populate it with items from an object which I have attempted several times but cannot get it. As you will see in my html file I already have the <ul></ul> tags with class of "grains". Per the instructions I am trying to create a loop to loop over the object and append each value to the <li> so they can show in my html.

The final output should be:

Final product

Here is my index.html:

<!DOCTYPE html>
<html lang="en-ca">
<head>
  <meta charset="utf-8">
  <title>Grain globber</title>
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <link href="css/main.css" rel="stylesheet">
</head>
<body>

  <h1>Grains</h1>
  <ul class="grains"></ul>

  <script src="jquery.min.js"></script>
  <script src="js/grains.js"></script>
  <script src="js/main.js"></script>
</body>
</html>

Here is my grains.js which holds my object:

var grains = [
  {
    name: 'Peanuts',
    img: 'peanuts.jpg',
    desc: 'First cultivated in the valleys of Paraguay.'
  },
  {
    name: 'Beans',
    img: 'beans.jpg',
    desc: 'A summer crop that needs warm temperatures.'
  },
  {
    name: 'Lentils',
    img: 'lentils.jpg',
    desc: 'An edible pulse from a bushy annual plant.'
  }
];

Here is my main.js file where I am attempting to complete the task but am stuck on:

$('.grains').each(function(){
    document.write($(this).text(grains) + "\n")
});

$("ul").each(function(grains) {
    for(var i = 0; i < grains.length;i++){
        grains[i].name;
        grains[i].img;
        grains[i].desc;
        if (('body').hasClass('grains')) {
        $('ul').append('<li>'+grains[i].name+'</li>'+'<li>'+grains[i].img+'</li>'+'<li>'+grains[i].desc+'</li>');
    }


    }

});

And this is my output:

output

I know I can get it done this way (see below) but I need to use a loop:

var $list = $('.grains');
$list.append('<h2>' + grains[0].name + '</h2>');
$list.append('<img src="images/peanuts.jpg">');
$list.append('<p>' + grains[0].desc + '</p>');

$list.append('<h2>' + grains[1].name + '</h2>');
$list.append('<img src="images/beans.jpg">');
$list.append('<p>' + grains[1].desc + '</p>');

$list.append('<h2>' + grains[2].name + '</h2>');
$list.append('<img src="images/lentils.jpg">');
$list.append('<p>' + grains[2].desc + '</p>');

Here are the instructions:

With an already made array of grains, create a layout in the HTML with jQuery & CSS.

  • Fork this repository.
  • The information is inside an array of objects in the grains.js file.
  • Loop over the grains variable and use jQuery to output <li> tags into the <ul> that’s already in the HTML file.
  • Each <li> tag should have an <img>, an <h2>, & a <p>
  • Style the Javascript generated list using CSS—the selectors are all ready.
  • DO NOT change the HTML.
  • DO NOT change grains.js
  • Run it through Markbot and make sure it passes all the checks.

Goal

Visually match the images in the “screenshots” folder.

I just need some guidance on getting the loop to work.

5
  • 2
    Is this homework mate? Commented Jul 13, 2018 at 17:54
  • @bassxzero - I think that's pretty self-evident from the "instructions". Homework questions are an interesting and somewhat contentious issue. I highly recommend reading this post: meta.stackoverflow.com/a/334823/211627 Commented Jul 13, 2018 at 17:57
  • 5
    @bassxzero Why does it matter if its homework? It is not as if OP is asking us to do his homework for him. He identified the problem, provided background, and needs help with the problem he's encountering. Nothing wrong with the question Commented Jul 13, 2018 at 17:57
  • 1
    @chevybow is correct. StackOverflow's very own What topics can I ask about? page clarifies this: "Questions asking for homework help must include a summary of the work you've done so far to solve the problem, and a description of the difficulty you are having solving it." Jermaine's question is more than accommodating in this regard. Commented Jul 13, 2018 at 18:03
  • Just to be clear this is not homework I am actually learning more about jquery and the DOM this is a mini project which I have shown I have attempted something and I knew what I needed to do it just was not clicking for me so I needed to reach out to the community to see if I could get some help. If it was homework as long as I am attempting to do the work I should be able to post. I know people on here that post test questions, interview questions, et cetera what makes mine any different? I would understand if I just posted the instructions and said solve it for me. Commented Jul 13, 2018 at 18:09

4 Answers 4

3

I was able to play around with it and solved it using this:

var $list = $('.grains');
function loopIt(){
   for(var i=0; i<grains.length; i++){
      $list.append('<li><h2>' + grains[i].name + '</h2></li>');
      $list.append('<li><img src=' + grains[i].img +'></li>');
      $list.append('<li><p>' + grains[i].desc + '</p></li>');
   }
}
loopIt();
Sign up to request clarification or add additional context in comments.

1 Comment

glad you figured it out
1

You're getting [object Object] because grains is an array of objects.

Rather than mutating the DOM in a loop, I would recommend building the html and then appending it just once.

let html = '';

$.each(grains, (index, grain)=> {
    html += `<li><img src="${grain.img}"><h2>${grain.name}</h2><p>${grain.desc}</p></li>`
});

$('.grains').html(html);

https://jsfiddle.net/09uvxh2s/8/

Comments

0

The real challenge you're looking at here is looping over an array. Once you've got that working it's simply appending the data in the current index over and over. The first solution would be a simply for loop.

for (let i = 0; i < grains.length; i++) { ... }

Another option would be looking into the new ES6 way of looping over arrays. I would suggest reading up on ForEach.

grains.forEach(grain => { ... })

Inside these loops simply write the code you're repeating in your snippet.

Comments

0

You are on the right track, but it's important to understand what you are iterating through when you loop .each().

When you write $('.grains').each, you are stating, loop through each HTML class element class "grains". Which is not what you want to do. Part of the confusion is your class is called grains, and your variable is called grains. I think that's a bad choice (and I know not your fault).

What you want to do is loop through your variable called grains. See example below.

var grains = [
  {
    name: 'Peanuts',
    img: 'https://nuts.com/images/auto/801x534/assets/dd79402e574cd109.jpg',
    desc: 'First cultivated in the valleys of Paraguay.'
  },
  {
    name: 'Beans',
    img: 'https://www.rd.com/wp-content/uploads/2014/02/03-beans-lower-cholesterol-sl.jpg',
    desc: 'A summer crop that needs warm temperatures.'
  },
  {
    name: 'Lentils',
    img: 'https://5.imimg.com/data5/KV/EJ/MY-27379132/organic-masoor-dal-500x500.jpeg',
    desc: 'An edible pulse from a bushy annual plant.'
  }
];

grains.forEach(function(grainType) {
  $('.grains').append('<li><img src="' + grainType.img + '"><div><h2>' + grainType.name + '</h2><p>' + grainType.desc + '</p></div></li>');
});
ul {
 list-style-type: none;
}

ul li {
  margin-top: 20px;
}

ul div {
  display: inline-block;
  max-width: 170px;
}

ul img {
  max-width: 70px;
  vertical-align: top;
}

ul div {
 margin-left: 5px;
}

ul div h2 {
  margin: 0px;
  font-weight: bold;
  font-size: 14px;
}

ul div p {
  margin: 0px;
  font-style: italic;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<!DOCTYPE html>
<html lang="en-ca">
<head>
  <meta charset="utf-8">
  <title>Grain globber</title>
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <link href="css/main.css" rel="stylesheet">
</head>
<body>

  <h1>Grains</h1>
  <ul class="grains"></ul>

  <script src="jquery.min.js"></script>
  <script src="js/grains.js"></script>
  <script src="js/main.js"></script>
</body>
</html>

PS - I didn't have access to your image, so I just got some images from the web.

6 Comments

Homework questions are held to the same standard as any other question. Your answer should account for the idea that it may or may not be homework. They're included in StackOverflow's What topics can I ask about?.
So you're going to dock me -2 for trying to help!?
If you're going to provide "tips" instead of an answer, at least explain them adequately.
I can only vote once, so I'm responsible for -1 of your score, yes. The reason being is that you've submitted an answer that isn't an answer, which you've acknowledged in the first line: "...instead of answering...". If you fix it up and actually provide an adequate answer I'll gladly reconsider my downvote. As it stands though, I think it's warranted. In the future, tips aren't bad, they're just not answers. In some cases (not always), they can be helpful as comments.
This is essentially a code-only answer. Code-only answers are on thin ice to begin with. This one doesn't even answer the question (by your own admission). See this meta post: meta.stackexchange.com/a/95473/191410
|

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.