Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I output an array in sequence to various div's?

I have tried many methods, the latest gives no output. Here are my codes. At other attempts, I got the array to display but not as wanted. Examples of how it’s to display are these(I capitalized the strings which are from the array): 

NOTE, each is a separate div which has been looped to give them similar attributes like class, The array output with the strings is added as the text content of each of the divs

My best output

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The FIRST SECOND THIRD question

The FIRST SECOND THIRD question

The FIRST SECOND THIRD question

Expected Output

The FIRST question

The SECOND question

The THIRD question

const myArr = ['first', 'second', 'third'];
for (let o = 0; o < myArr.length; o++) {
  console.log(`The ${myArr[o]} question`)

  const divOne = document.querySelectorAll('.eachSection-class div:nth-of-type(1)');
  for (j = 0; j < divOne.length; j++) {
    divOne[j].classList.add('divOne-class');
    divOne[j].textContent = `The ${myArr[o]} question`;
  }
  console.log(divOne);
}
<body>
  <main>
    <section>
      <div></div>
      <div></div>
    </section>
    <section>
      <div></div>
      <div></div>
    </section>
    <section>
      <div></div>
      <div></div>
    </section>
  </main>

>Solution :

I am not totally sure what you want the code to do, but this will likely give you enough to do what you want

const main = document.querySelector('main'); 
main.classList.add('main-class');
const sections = document.querySelectorAll('main section');
sections.forEach(section => section.classList.add('eachSection-class'));

const myArr = ['first', 'second', 'third'];
myArr.forEach((val,i) => {
  const content = `The ${val} question`;
  console.log(content)
  const firstDiv = sections[i].querySelector('div'); // assuming as many sections as array length
  firstDiv.classList.add('divOne-class');
  firstDiv.textContent = content;
})
.divOne-class { border: 1px solid red; }
<body>
  <main>
    <section>
      <div></div>
      <div>First section, second div</div>
    </section>
    <section>
      <div></div>
      <div>Second section, second div</div>
    </section>
    <section>
      <div></div>
      <div>Third section, second div</div>
    </section>
  </main>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading