简体   繁体   中英

Loop through array and append to different HTML elements

I have 3 HTML columns and an array with 3 objects within it. I'm trying to loop through the array and append the value within the array to each of the HTML column. So the first object in the array to the first column ,second object to the second column. Which type of loop would be best for this scenario?

 var shortenedCast = fullCast.slice(0, 3); var arrayLength = shortenedCast.length; //3 var columns = document.getElementsByClassName("panel-item"); var characterP = document.getElementsByClassName("character"); for (var i = 0; i < arrayLength; i++) { console.log(shortenedCast[i].character); //John wick //Viggo Tarasov //Iosef Tarasov characterP.textContent = shortenedCast[i].character; } console.log(shortenedCast); 
 <div class="column small-4"> <div class="panel-item"> <p class="character"></p> </div> </div> <div class="column small-4"> <div class="panel-item"> <p class="character"></p> </div> </div> <div class="column small-4"> <div class="panel-item"> <p class="character"></p> </div> </div> 

I'm thinking maybe a more dynamic approach without having to add new Divs every time you increase the array.

arr = ['John wick', 'Viggo Tarasov', 'Iosef Tarasov'];

function createColumns(arr) {
  let colItems = [];

  arr.map(item => {
    colItems.push(`
      <div class="column small-4">
        <div class="panel-item">
          <p class="character">${item}</p>
        </div>
      </div>
      `);
  });

  return colItems;
}

document.getElementById('someDivID').innerHTML = createColumns(arr).join('');

Thanks Heretic Monkey that worked

For people viewing the solution was to add [i] in front of the characterP

var fullCast = credits.cast;


var shortenedCast = fullCast.slice(0,3);
var arrayLength = shortenedCast.length;
var columns = document.getElementsByClassName("panel-item");
var characterP = document.getElementsByClassName("character");

    for (var i = 0; i < arrayLength; i++) {
        console.log(shortenedCast[i].character);  
        characterP[i].textContent = shortenedCast[i].character;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM