Jump to content

Element has no properties error.


Err

Recommended Posts

I'm using this JavaScript to target classes in order to hide/show various things on the page depending if JavaScript is enabled or disabled.

var show = document.getElementsByTagName("div");for(i=0;i<=show.length;i++) {  if (show[i].className == "download") {	show[i].style.display = "block";  }}

When I use that code and check my error console in FF, I get a "show has no properties" error, is there something wrong in my script? Despite having errors, the script still works as intended.See the page here: http://oneuse.awardspace.com/test/test_g1.htmlAlso, I have two of these scripts, another problem that I'm having is that I can't put two of these scripts in the same <script> tag. I have to separate them in different <script> tags or else it won't work.

Link to comment
Share on other sites

That is because show's index will start at 0, and end at its length - 1. However, the length function will return the number of elements in show. So, if show had 6 elements, show.length would = 6, while the maximum subscript would be 5. In your code, though, i will continue to be incremented to 6, and as show[6] does not exist, JS throws an error. This will fix it:

var show = document.getElementsByTagName("div");for(i=0;i<show.length;i++) {  if (show[i].className == "download") {	show[i].style.display = "block";  }}

Link to comment
Share on other sites

Thank you so much. So this code couldn't be <= show.length, just less than, without the equal to. Ah, well thanks for fixing it. This also solved my another problem. :)

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...