0
var toBeHidden_letter = document.getElementsByClassName('doc_direction');
for(var i = 0; i < 10; i++) {
    toBeHidden_letter[i].style.display = 'block';
    alert('i = '+i);
}  

I only have 2 alerts. why?

Edited : I have 10 elements of class = 'doc_direction' in my HTML.

5
  • 1
    Show your HTML. My guess would be you only have 2 elements which match the class. After this, the javascript is returning a reference error Commented Nov 26, 2012 at 11:59
  • Are you sure that you have 10 elements with the class "doc_direction"? If you have only 2, the for-loop runs twice and then fails because there is no third index in toBeHidden_letter. Commented Nov 26, 2012 at 12:00
  • Open your JavaScript console and check if you are getting any errors. I suspect that getElementsByClassName only returns 2 elements, and so your loop will error out on the third iteration ... Commented Nov 26, 2012 at 12:00
  • Does it throw any error? How can you be sure that you have 10 items in the collection? You would be much better to loop using the length of the list returned, not a static number. Commented Nov 26, 2012 at 12:00
  • I have 10 elements of class = 'doc_direction' Commented Nov 26, 2012 at 12:06

2 Answers 2

3

I think you need :

var toBeHidden_letter = document.getElementsByClassName('doc_direction');
for(var i = 0; i < toBeHidden_letter.length; i++) {
    toBeHidden_letter[i].style.display = 'block';
    alert('i = '+i);
} 
Sign up to request clarification or add additional context in comments.

Comments

0

Seems that you have only two elements with .doc_direction class name and JS causes errors, can you check console for errors and provide some HTML?

BTW better is to get length of elements instead of hardcoded number 10:

for(var i = 0; i < toBeHidden_letter.length; i++) {

Comments

Your Answer

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