2

I have a little Javascript problem. Instead of using this:

document.getElementById("hoverinv1").style.display = "";
document.getElementById("hoverinv2").style.display = "";
document.getElementById("hoverinv3").style.display = "";
document.getElementById("hoverinv4").style.display = "";
document.getElementById("hoverinv5").style.display = "";
document.getElementById("hoverinv6").style.display = "";
document.getElementById("hoverinv7").style.display = "";
document.getElementById("hoverinv8").style.display = "";
document.getElementById("hoverinv9").style.display = "";
document.getElementById("hoverinv10").style.display = "";

I wanted to use this:

for (var x = 0; x < 11; x++) {
    document.getElementById("hoverinv" + x).style.display="";
}

To display again everything. Well, it does nothing and I have no idea whats the problem.

3
  • 2
    give your elements a class instead? Commented Nov 10, 2014 at 15:41
  • 4
    x should start from 1 not 0 Commented Nov 10, 2014 at 15:42
  • 3
    Look at the console. Commented Nov 10, 2014 at 15:43

3 Answers 3

6

It's probably throwing an error on the first iteration because hoverinv0 does not exist. You want

for (var x = 1; x < 11; x++) {
  document.getElementById("hoverinv" + x).style.display="";
}
Sign up to request clarification or add additional context in comments.

Comments

0

Your first code starts with "hoverinv1" and in your loop you start with "hoverinv0".

Probably, it is not finding the element, returning undefined and then your script crashes when you try to access style property.

Check the browser's console, it should emit an error or something.

Comments

0

Do it simply in CSS:

[id^=hoverinv] {
  display: block; /* or any other needed display value */
}

Your issue: by inspecting your JS in Console you can clearly see that it breaks while fetching your hoverinv0 ID element (does not exists).

What you can:

assign a class class="hoverinv" to all your element and go for:

var hoverInv = document.getElementsByClassName("hoverinv");
for (var i=0; i<hoverInv.length; i++){
     hoverInv[i].style.display = "";
}

or using

var hoverInv = document.querySelectorAll("[id^=hoverinv]");
for (var i=0; i<hoverInv.length; i++){
     hoverInv[i].style.display = "";
}

or something you might go fix all over again as soon you change the number of elements:

for(var i=1; i<11; i++){
   document.getElementById("hoverinv"+ i).style.display = "";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.