skip to Main Content

I am for looping an HTMLCollection with the goal of updating the style of every p tag. My problem is that I get Invalid left-hand side in assignment expression and I don’t know why.

var getp = document.getElementsByClassName(currentUser[0]?.username)
   for (let i of getp) {
       console.log(i?.style);
       i?.style.background = 'red'
}

4

Answers


  1. You cannot assign a value to possibly undefined property. Instead of using optional chaining, you could use simple if condition:

    if (i) {
      i.style.background = 'red';
    }
    
    Login or Signup to reply.
  2. It is very simple just remove left-hend side ?

    from

    i?.style.backgroundColor = 'red'
    

    to

        i.style.backgroundColor = 'red'
    

    thanks

    Login or Signup to reply.
  3. you can use the for loop with an Array or just a regular for loop like this

    var getp = document.getElementsByClassName(currentUser[0]?.username);
    for (let i = 0; i < getp.length; i++) {
      console.log(getp[i].style);
      getp[i].style.background = 'red';
    }
    

    tested and working perfectly

    Login or Signup to reply.
  4. We can simple use for loop to resolve this issue

    var getp = document.getElementsByClassName(currentUser[0]?.username);
    for (let i = 0; i < getp.length; i++) {
        var pElement = getp[i];
        console.log(pElement.style);
        pElement.style.background = 'red';
    }
    

    It will work perfectly.

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