Home > Back-end >  looping an array and distributing the results to three different paragraphs
looping an array and distributing the results to three different paragraphs

Time:06-13

I have an array of 0-3 name values. I need to loop through my array and write the values to 3 different <p> with different class names.

Not sure how to use innerHTML to assign the data values to individual divs. Plenty of info online about how to write all the data to a single div but not multiples (that i could find).

Here is the principle code...

const dataResults = ['Apple', 'Orange', 'Pear']

for (var i = 0; i < dataResults.length; i  ) {
  //how to distribute these results to V1, V2 and V3???
  console.log(dataResults[i]);
}
<div >
  <p >-</p>
  <p >-</p>
  <p >-</p>
</div>

As a closing bonus I will also need to empty the array after it has completed its task.

CodePudding user response:

You should dynamically build selector from your loop index:

const dataResults = ['Apple', 'Orange', 'Pear']

for (var i = 0; i < dataResults.length; i  ) {
       el = document.querySelector('.v'   (i   1));
       text = document.createTextNode(dataResults[i]);
       el.appendChild(text);

       console.log(dataResults[i]);
}
<div >
  <p >-</p>
  <p >-</p>
  <p >-</p>
</div>

CodePudding user response:

const dataResults = ['Apple', 'Orange', 'Pear'];
for (var i = 0; i < dataResults.length; i  ) {
    document.querySelector(".v"   (i   1)).innerHTML = dataResults[i];
}
<div >
    <p >-</p>
    <p >-</p>
    <p >-</p>
</div>

CodePudding user response:

One solution to the above problem is by storing the <p> tags in the list and adding the elements in it. Like:

const dataResults = ['Apple', 'Orange', 'Pear']


let d = document.getElementsByClassName('selections')[0]
let p = d.children;
let count = d.childElementCount;


for (var i = 0; i < dataResults.length; i  ) {
  p[i%count].innerHTML = dataResults[i]
  console.log(dataResults[i]);
}
<div >
  <p >-</p>
  <p >-</p>
  <p >-</p>
</div>

  • Related