I'm new to JavaScript and I want to do this: I have an array with objects (an object has a title, cover, author and rating) and I want to populate divs with these objects, one div per object. But I don't know how can I do this without creating new elements (h1, p, img) for every div. This is my first attempt:
// Display the books
var container = document.getElementById('books-container');
function displayBooks(arr) {
arr.forEach(function(item) {
var bookRow = document.createElement('div');
bookRow.className = "row";
container.appendChild(bookRow);
var imgColumn = document.createElement('div');
imgColumn.className = "large-4 columns";
bookRow.appendChild(imgColumn);
var imgBook = document.createElement('img');
imgBook.className = "book-img";
imgColumn.appendChild(imgBook);
var bookColumn = document.createElement('div');
bookColumn.className = "large-8 columns";
bookRow.appendChild(bookColumn);
var title = document.createElement('h3');
title.innerText = item.title;
bookColumn.appendChild(title);
var author = document.createElement('p');
author.innerText = item.author;
bookColumn.appendChild(author);
var rating = document.createElement('p');
rating.innerText = item.rating;
bookColumn.appendChild(rating);
var input = document.createElement('input');
input.type = "checkbox";
input.className = "checked";
bookColumn.appendChild(input);
var wishBtn = document.createElement('button');
wishBtn.innerText = "Add to wishlist";
bookColumn.appendChild(wishBtn);
var hr = document.createElement('hr');
bookRow.appendChild(hr);
});
};
displayBooks(books);
But I think there is a simpler method to this.
I cannot use any libraries. This is a homework assignment, I can only use the functions and objects provided by JavaScript itself.