Search code examples
javascripthtmlgoogle-books

How to create multiple HTML elements from an Array?


I have a simple site that is getting a list of books from the Google Books API. I have a separate file called scripts.js that is getting all the book information (title, author, ISBN, link to the image).

I want to create a div for each book in a gallery style page, where there is a picture of the book and on top of the book is the Title, Author, and ISBN.

I've tried creating the DIV's in Javascript but I want there to be an h3, p, and img inside of each DIV and I can't seem to wrap my head around how I could do that in Javascript.

My HTML code for the gallery:

<div id="content">
            <h2>My Bookshelf</h2>
            <div class="book">
                <!-- The book image is the background of the div -->
                <h3 class="book-title">Title</h3>
                <p class="book-isbn">ISBN: 000000</p>
                <p class="book-author">Authors: ABC</p>
            </div>
        </div>

My Javascript code that cycles through the JSON file and returns the needed information.

// Returns an array with the book title, ISBN, author, bookmark icon, description, image 
    apiRequest.onreadystatechange = () => {
        if (apiRequest.readyState === 4) {
            const response = JSON.parse(apiRequest.response);
            var bookList = response.items;
            // Removes old search results before display new ones
            bookSection.innerHTML = "";
            for (let i = 0; i < bookList.length; i++) {
                console.log(i);
                var title = (bookList[i]["volumeInfo"]["title"]);
                try {
                    var isbn = (bookList[i]["volumeInfo"]["industryIdentifiers"][0]["identifier"]);
                } catch (TypeError) {
                    var isbn = "ISBN Not Available";
                }
                var author = (bookList[i]["volumeInfo"]["authors"]);
                var description = (bookList[i]["description"]);
                try {
                    var image = (bookList[i]["volumeInfo"]["imageLinks"]["thumbnail"]);
                } catch (TypeError) {
                    var image = "img/unavailable.png";
                }
            }
        }
    }

Solution

  • You can use template literals to make your job easier.

    You can do it like this:

    var bookSection = `<div id="content">
            <h2>My Bookshelf</h2>
            <div class="book">
                <!-- The book image is the background of the div -->
                <h3 class="book-title">${titleVar}</h3>
                <p class="book-isbn">ISBN: ${ISBNVar}</p>
                <p class="book-author">Authors: ${AuthorsVar}</p>
            </div>
        </div>`;
    

    Learn more about template literals from here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals