user1015711
user1015711

Reputation: 132

Why is this coming up null

I get a null error on the line this

document.getElementById("Attachment" + x).style.display = "none";

I really dont want to write this out 5 times. The line does work if i do this.

document.getElementById("Attachment1").style.display = "none";

What am i missing here? To keep this short i only included the loop where ther error is.

for (x = 0; x < 5; x++)
{

  if(showHideArray[x] &gt; 0) 
  {
    document.getElementById("Attachment" + x).style.display = "none";
  }
  else {
        document.getElementById("Attachment" + x + "If").style.display = "none";
       }

}

Upvotes: 0

Views: 171

Answers (3)

Esailija
Esailija

Reputation: 140210

You are trying to access property style of null, this will throw an error. Check that the element exists before trying to access properties.

for (x = 0; x < 5; x++) {
    var elem = document.getElementById("Attachment" + x + (showHideArray[x] > 0 ? "If" : "" ) );

    if( elem ) {
        elem.style.display = "none";
    }
}

Upvotes: 0

chantheman
chantheman

Reputation: 5286

If there is no element with the given id, this function returns null. So if I was you I would print out document.getElementById("Attachment" + x).style.display = "none";

Show us what it outputs. But one solution that will prob work is:

for (x = 0; x < 5; x++)
{

  if(showHideArray[x] &gt; 0) 
  {
    var y = "Attachment" + x;
    document.getElementById(y).style.display = "none";
  }
  else {
        var z = "Attachment" + x + "If";
        document.getElementById(z).style.display = "none";
       }

}

I would try both those things.

Upvotes: 0

SLaks
SLaks

Reputation: 887275

You probably don't have an element with ID Attachment0.

Upvotes: 3

Related Questions