This J fiddle utilizes getElementsByClassName
This j fiddle uses getElementByID
when I print out the length of the var "x".... the length is different for the class and id versions. The id version actually spits out the correct value which is 4... rather than 1.... which class spits out.
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.
Returns a reference to the element by its ID.
length returns the number of items in a NodeList.
now in your jsfiddles..
document.getElementsByClassName("mySelect" ).length is 1.. why?
document.getElementsByClassName .. returns a set of elements.. i.e an Array.. and as there are only one element with class name "mySelect" the length of the array wil be 1
document.getElementById("mySelect" ).length is 4. why?
document.getElementById returns a refrence to the element and as there are four elements in the nodelist of the element.. (in your case 4
<option> s) so Element.length will return 4..
GetElementsByClassName is returning a set of length 1, so you need to get the first element of the set and ask for its length.
GetElementById gives you the element directly, and you then ask for its length, which gives you the number of children.
The difference is that when you are performing
getElementByID, you are being returned a single DOM element which has that ID. When you are performing
getElementsByClassName, you are being returned a
NodeList which contains any DOM element that has that class name assigned to it. So, when you are doing x.length with
getElementsByClassName you are actually doing NodeList.length which is 1.
What I think you actually want is
var x = document.getElementsByClassName("mySelect").length; or some variation of that.