How to set innerHTML in javascript?

How to apply for loop in javaScript and append all the li into paginationWrapper innerHTML. I tried below approach it does append only one by replacing the previous inner html

Here is my HTML

<nav aria-label="Page example">
    <ul class="pagination"></ul>
</nav>
const paginationWrapper = document.querySelector(".pagination");
let currentBatch = 1;
let pageButtonList = [1,2,3,4,5];
paginationWrapper.innerHTML= "";
for (let page = 0; page <= pageButtonList.length; page++){
    if(pageButtonList[page] === currentBatch){
        paginationWrapper.innerHTML = `<li className="page-item active"><button onclick="clickedButtonData(event)" value=${pageButtonList[page]} className="page-link">${pageButtonList[page]}</button></li>`;
    } else {
        paginationWrapper.innerHTML = `<li className="page-item"><button onclick="clickedButtonData(event)" value=${pageButtonList[page]}className="page-link">${pageButtonList[page]}</button></li>`;
    }
}

Answer

You keep overwriting the same innerHTML on paginationWrapper. I think you want to use .append() or perhaps paginationWrapper.innerHTML = paginationWrapper.innerHTML + '<new content>'

Alternatively you could make the full list of child elements as a string and then use .innerHTML

paginationWrapper.innerHTML = pageButtonList.map(page => {
  if(pageButtonList[page] === currentBatch) {
    return `<li className="page-item active"><button onclick="clickedButtonData(event)" value=${page} className="page-link">${page}</button></li>`;
  } else {
    return `<li className="page-item"><button onclick="clickedButtonData(event)" value=${page} className="page-link">${page}</button></li>`
  }
}).join('');

Leave a Reply

Your email address will not be published. Required fields are marked *