Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getElementsByClassName produces error "undefined" [duplicate]

Tags:

javascript

I have several textboxes with the class output. I would like to be able to print their values as a plain HTML list in a div with ID combined. Right now, I have the following code:

function doCombine() {
    document.getElementById('combined').innerHTML =
    document.getElementsByClassName('output').value + ",";  
}

Yet, when I run the function, i get the error message undefined,. When i add a [0] before .value, it works, but only the value of the first textbox is showing up. I read somewhere that [i] will show all the values, but that doesn't seem to work.

What am I doing wrong?

like image 753
user2863271 Avatar asked Oct 10 '13 07:10

user2863271


2 Answers

getElementsByClassName

Returns a set of elements which have all the given class names. When called on the document object, the complete document is searched, including the root node. You may also call getElementsByClassName on any element; it will return only elements which are descendants of the specified root element with the given class names.

So you should be doing

var elements = document.getElementsByClassName('output');
var combined = document.getElementById('combined');
for(var i=0; i < elements.length; i++) { 
  combined.innerHTML += elements[i].value + ",";
}
like image 122
Deepak Ingole Avatar answered Nov 02 '22 03:11

Deepak Ingole


getElementsByClassName returns an array-like object, not a single element (notice the plural in the name of the function). You need to iterate over it, or use an array index if you just want to operate on the first element it returns:

document.getElementsByClassName('output')[0].value + ","
like image 24
Barmar Avatar answered Nov 02 '22 02:11

Barmar