Home > database >  how to inject last 2 elements of an array into html
how to inject last 2 elements of an array into html

Time:06-26

I'm creating a book store. I need to inject 10 elements from an array into the html, 8 of them into 1 section and the last 2 in a 'featured' section.

My current JS file is printing the correct stuff into my html, but i'm having trouble getting the last 2 injected into the featured section.

fetch('https://www.googleapis.com/books/v1/volumes?q=HTML5')
    .then(response => response.json())
    .then(data => console.log(data));

function handleResponse(obj) {
    obj.items.forEach((item, index) => {
        if (index > 7) return; // returns 8 elements from array
        let div = document.createElement('div');
        div.className = 'books';
        div.innerHTML = `<img src="${item.volumeInfo.imageLinks.thumbnail}"  alt="${item.singleTitle} by ${item.volumeInfo.authors[0]}" />
            <h4>${item.volumeInfo.title}</h1>
            <p><strong>${item.volumeInfo.authors}</strong></p>
            <h8>${item.volumeInfo.description}</h8>
            <br>
            <br>
            <h8>Pages:  ${item.volumeInfo.pageCount}</h8>`

        let container = document.querySelector('.booklist-cards');
        container.append(div);
    })
}

The code where I would like to inject the last 2 into my html is

<div>
    <div>
        <div >
            <h1>Featured</h1>
            <div >
                book1
            </div>
            <div >
                book2
            </div>
        </div>
    </div>
</div

I also need to limit the description to 140 characters.

CodePudding user response:

If we are expecting exactly 10 books in the response, we can split the array into otherBooks and featuredBooks using Array.prototype.splice() like this:

  const otherBooks = data.items
  const featuredBooks = otherBooks.splice(8, 10)

fetch('https://www.googleapis.com/books/v1/volumes?q=HTML5')
  .then(response => response.json())
  .then(data => handleResponse(data));

function handleResponse(data) {
  const featuredContainer = document.querySelector('.featured-books');
  const otherContainer = document.querySelector('.other-books');
  const otherBooks = data.items
  const featuredBooks = otherBooks.splice(8, 10)
  featuredContainer.insertAdjacentHTML('beforeend', renderListHtml(featuredBooks))
  otherContainer.insertAdjacentHTML('beforeend', renderListHtml(otherBooks))
}

function renderListHtml(items) {
  return items.map(item => renderItemHtml(item)).join('')
}

function renderItemHtml(item) {
  return `<li ><img src="${item.volumeInfo.imageLinks.thumbnail}" alt="${item.singleTitle} by ${item.volumeInfo.authors[0]}" /><div><h4>${item.volumeInfo.title}</h4>${item.volumeInfo.authors}</div></li>`
}
.book {
  display: flex;
  padding: 10px;
  gap: 10px;
}
<h1>Featured</h1>
<ul ></ul>

<h1>Other</h1>
<ul ></ul>

  • Related