hummmingbear
hummmingbear

Reputation: 2384

Display JavaScript Object in HTML

I have a object that looks like this:

var grocery_list = {
  "Banana": { category: "produce", price: 5.99 },
  "Chocolate": { category: "candy", price: 2.75 },
  "Wheat Bread": { category: "grains and breads", price: 2.99 }
}

And I want to be able to display each item in the object in HTML like this:

<div id="grocery_item" class="container">
    <div class="item">Item Here</div>
    <div class="category">Category Here</div>
    <div class="price">Price Here</div>
</div>

I know how to loop through an Object in JS, but I'm not sure how to display those items in the DOM. I believe I could use the jQuery append function but I'm not sure how.

Any help would be appreciated. thanks!

Upvotes: 7

Views: 49611

Answers (5)

Anh-Thi DINH
Anh-Thi DINH

Reputation: 2364

It's old but you can try package html-stringify. As its introduction: "Converts Javascript Objects or Arrays to pretty HTML string for rendering in a browser."

Upvotes: 1

Ivan Sivak
Ivan Sivak

Reputation: 7488

This is how you can do it using jQuery (as you mention you'd like to use jQuery first). But it's not the best way how to it. If you're open to learn better methods then check some of the MV* frameworks (AngularJS, Ember etc.). Anyway, here is just an example:

var grocery_list = {
  "Banana": { category: "produce", price: 5.99 },
  "Chocolate": { category: "candy", price: 2.75 },
  "Wheat Bread": { category: "grains and breads", price: 2.99 }
}

var wrapper = $('#wrapper'), container;
for (var key in grocery_list){
    container = $('<div id="grocery_item" class="container"></div>');
    wrapper.append(container);
    container.append('<div class="item">' + key +'</div>');
    container.append('<div class="category">' + grocery_list[key].category +'</div>');
    container.append('<div class="price">' + grocery_list[key].price +'</div>');
}

jsfiddle here: http://jsfiddle.net/5jhgbg9w/

EDIT: Please, take this really as an example (which is OK since you're learning). As others pointed out - it's not the best method. Try to combine other examples, particularly the ones which do not compose HTML as a string. For easy tasks like this it's straightforward but the more code you would add, the messier the code becomes. I believe your "learning evolution" would get you there anyway :-) Cheers everyone

EDIT (2021): A lot of years have gone by since I answered this question. What about some more modern examples, just for fun? Without jQuery, just ES6:

const grocery_list = {
  "Banana": { category: "produce", price: 5.99 },
  "Chocolate": { category: "candy", price: 2.75 },
  "Wheat Bread": { category: "grains and breads", price: 2.99 }
};

// since "grocery_list" is an object (not an array) we have do Object.keys()
const generatedHtml = Object.keys(grocery_list).reduce((accum, currKey) => accum +
  `<div class="grocery_item">
    <div class="item">${currKey}</div>
    <div class="category">${grocery_list[currKey].category}</div>
    <div class="price">${grocery_list[currKey].price}</div>
  </div>`, '');

document.getElementById('container').innerHTML = generatedHtml;
.grocery_item{
  padding: 5px;
}
.grocery_item:not(:last-child){
  border-bottom: 1px solid #ccc;
}
<div id="container"></div>

Upvotes: 9

Alexandru Aliu
Alexandru Aliu

Reputation: 474

I will pass by the fact that your list definition is not exactly the best and I say this:

Using jQuery you could do that:

<script>
var _parent = $(".container").parent();
_parent.empty();

var _html;
$.each(grocery_list,function(prop, val){
    _html = "<div id=\"grocery_item\" class=\"container\">";
    _html += "<div class=\"item\">"+prop+"</div>";
    _html += "<div class=\"category\">"+val.category+"</div>";
    _html += "<div class=\"price\">"+val.price+"</div>";
    _html += "</div>";

    _parent.append(_html);
});
</script>

Note*: It's not recomanded to maanipulate the DOM by creating HTML strings. This is just an fast sample for your school assignment.

Upvotes: 0

Ifch0o1
Ifch0o1

Reputation: 924

You can create HTML elements with jQuery: $('<div>', {attr1: value, attr2: value}); This returns a new jQuery object so you can use it like jQuery element.

The jQuery.text() method: $('div').text('some text') This method is recommended if you putting just text inside the element. It will escape all special characters like '<'. Instead it puts &lt. This avoiding XSS attacks unlike jQuery.html() method. You can look Security Considerations at jQuery docs about .html method.

// Create a div element with jQuery which will hold all items.
var $tree = $('<div>', {id: 'items-tree'});
//Loop all items and create elements for each
for (var key in grocery_list) {
  var $gItem = $('<div>', {
    id: 'grocery_item',
    class: 'container'
  });

  var $item = $('<div>', {
    class: 'item'
  }).text(key);
  $gItem.append($item);

  var $category = $('<div>', {
    class: 'category'
  }).text(grocery_list[key].category);
  $gItem.append($category);

  var $price = $('<div>', {
    class: 'price'
  }).text(grocery_list[key].price);
  $gItem.append($price);

  $tree.append($gItem);
}

JSFiddle

Upvotes: 3

Raghava Rudrakanth P V
Raghava Rudrakanth P V

Reputation: 131

The parent div <div id="grocery_item" class="container"> will be repeated for the no. of items in the grocery list. The "id" of this parent div will be generated randomly for example item @index 0 will be "grocery_item0"

For each loop item create the parent div's first, then start appending the details to the parent div's using (another loop). Below will be sample jquery,

$( ".grocery_item0" ).append( "" );

Upvotes: 0

Related Questions