skip to Main Content

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 to let.
  • p.textContent = 'abc'
  • no forEach or map 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


  1. You for loop is going downwards, it should go upwards (should be i < ls.length not i > ls.length):

    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)
    Login or Signup to reply.
  2. Error:
    for (let i = 0; i > ls.length; i++)

    Correction:
    for (let i = 0; i < ls.length; i++)

    i is less then length

    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';
      if (i !== ls.length - 1) {
        p.textContent += ', ';
      }
    }
    console.log(p);
    Login or Signup to reply.
  3. You did a mistake: your loop was wrongly expecting i > ls.length which is false from beginning (correct one is i < ls.length)

    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'
      if (i < ls.length - 1) {
        p.textContent += ', '
      }
    }
    console.log(p)

    I hope it suits your needs.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search