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
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>