-1

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>
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
TF120
  • 297
  • 1
  • 3
  • 14
  • 1
    Possible duplicate of [What do querySelectorAll and getElementsBy\* methods return?](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-and-getelementsby-methods-return) – Heretic Monkey Mar 01 '19 at 17:13
  • 3
    You've already got it, it's just that `getElementsByClassName` returns an `HTMLCollection`, so you can do `characterP[i].textContent ...` – Heretic Monkey Mar 01 '19 at 17:14

2 Answers2

1

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('');
Shawn Yap
  • 969
  • 7
  • 12
0

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;
    }
TF120
  • 297
  • 1
  • 3
  • 14