I am trying to add textContent of a p element from inside a for-loop :
const ls = [1, 2, 3, 4, 5, 6]
const p = document.createElement('p')
p.classList.add('text-body-secondary')
for (let i = 0; i > ls.length; i++) {
p.textContent += 'abc'
// p.textContent = 'abc' // Does not work either.
if (i !== ls.length - 1) {
p.textContent += ', '
}
}
console.log(p)
expecting :
<p class="text-body-secondary">abc, abc, abc, abc, abc, abc</p>
But it did not work.
Here are what I have tried:
- I have changed
const
tolet
. p.textContent = 'abc'
- no
forEach
ormap
since I need to use index.
Is this not allowed to manipulate p.textContent from inside a for-loop?
How can I achieve this?
3
Answers
You for loop is going downwards, it should go upwards (should be
i < ls.length
noti > ls.length
):Error:
for (let i = 0; i > ls.length; i++)
Correction:
for (let i = 0; i < ls.length; i++)
i
is less thenlength
You did a mistake: your loop was wrongly expecting
i > ls.length
which is false from beginning (correct one isi < ls.length
)I hope it suits your needs.