Karan Siddannavar
Karan Siddannavar

Reputation: 49

Calling a function inside forEach

//Array of books

const books = [{
  title: 'The subtle art of not giving a fuck',
  author: 'Mark Manson'
},{
  title: 'Everything is fucked',
  author: 'Mark Manson'
},{
  title: 'Seriousness takes the joyfulness of life',
  author: 'Karan Siddannavar'
}]

const getBooks = book => {
  document.querySelector('.book-list').innerHTML = `<li>${book.title}</li>
<li>${book.author}</li>`
}

books.forEach(book => {
  getBooks(book);
})
<div class="book-list"></div>

I call the getBooks method every time the book variable is updated with a new object. But, the function gets called only once. In other words, the details of only one book is displayed, even though the function is called every time the forEach loops through the array. Why does this happen?

Upvotes: 0

Views: 1351

Answers (2)

Mamun
Mamun

Reputation: 68933

In each call of the function you are replacing the innerHTML (previous content with the current content), you have to use += instead of = to retain the previous HTML.

Though, I will suggest you to use Element.insertAdjacentHTML() instead of innerHTML:

const books = [{
  title: 'The subtle art of not giving a fuck',
  author: 'Mark Manson'
},{
  title: 'Everything is fucked',
  author: 'Mark Manson'
},{
  title: 'Seriousness takes the joyfulness of life',
  author: 'Karan Siddannavar'
}]

const getBooks = book => {
  document.querySelector('.book-list').insertAdjacentHTML('beforeend', `<li>${book.title}</li>
<li>${book.author}</li>`)
}

books.forEach(book => {
  getBooks(book);
})
<div class="book-list"></div>

Upvotes: 3

Nenad Vracar
Nenad Vracar

Reputation: 122155

You could use map method instead of forEach and first create content then add it to DOM so you don't have to access DOM in each iteration.

const books = [{
  title: 'The subtle art of not giving a fuck',
  author: 'Mark Manson'
}, {
  title: 'Everything is fucked',
  author: 'Mark Manson'
}, {
  title: 'Seriousness takes the joyfulness of life',
  author: 'Karan Siddannavar'
}]

const getBooks = ({title, author}) => `<li>${title}</li><li>${author}</li>`
const content = books.map(getBooks).join('');
document.querySelector('.book-list').innerHTML = content;
<div class="book-list"></div>

Upvotes: 0

Related Questions