0

Im triying of get all element by class name but i cannot get

when i try to get a one lement this command works

document.getElementsByClassName('div1')[5].value

but this command not works

var i=0;
for ( i < 6; i++) {
    x = document.getElementsByClassName('div1')[i].value ;
}
var elementHtml = x;

i obtain this error

SyntaxError: missing ; after for-loop condition index.html:9:16 ReferenceError: downloadDiv is not defined

i get this error also

****TypeError: document.getElementsByClassName(...)[i] is undefined[Saber más]


please somebody help me

=============================================================

i put the response thankyou for your answers

var i = 0;

var x = 0;
for(var i = 0; i < document.getElementsByClassName('div1').length; i++){    
    x = x + document.getElementsByClassName('div1')[i].value;
}
var elementHtml = x;
13
  • 2
    for(; i<6; i++) You missed semicolon as error says. You can remove var i = 0, and change for to: for(var i = 0; i < 6; i++) Commented Dec 3, 2016 at 21:10
  • 1
    The standard way to define for is defining the index var inside: for (var i=0; i < 6; i++) Commented Dec 3, 2016 at 21:12
  • i get this TypeError: document.getElementsByClassName(...)[i] is undefined[Saber más] Commented Dec 3, 2016 at 21:13
  • why wouldn't you just use querySelectorAll('.div1') and then loop through it and get the .value ? Commented Dec 3, 2016 at 21:14
  • 3
    @AlekseiMaide You mean querySelectorAll('.div1'). Commented Dec 3, 2016 at 21:16

1 Answer 1

1

You have made a mistake in your for loop in relation to your question;

for (var i=0; i < 6; i++) {
    x = document.getElementsByClassName('div1')[i].value;
}
var elementHtml = x;
Sign up to request clarification or add additional context in comments.

2 Comments

document.getElementsByClassName('div1') instanceof Array === false, so Array.prototype.forEach will not be available. Its type is HTMLCollection which is array-like, but not actually an array. developer.mozilla.org/en-US/docs/Web/API/Document/…
@connexo Though you can foreach through a HTMLCollection I think, Well you'd have to iterate anyways using a counter. Fair enough.