user2800382
user2800382

Reputation: 259

Difference between the length of id and class objects

This J fiddle utilizes getElementsByClassName

http://jsfiddle.net/YZTpn/

This j fiddle uses getElementByID

http://jsfiddle.net/9Fa89/

<script>

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.

Upvotes: 2

Views: 127

Answers (4)

Psych Half
Psych Half

Reputation: 1411

document.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.

Read More..

document.getElementById

Returns a reference to the element by its ID.

Read More

Element.length

length returns the number of items in a NodeList.

Read More

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..

Upvotes: 3

Mindfull
Mindfull

Reputation: 17

maybey you could try this instead:

<script>
function displayResult()
{
var x=document.getElementsByName('Select');
alert(x.length);
}
</script>
</head>
<body>

<form>
Select your favorite fruit:
<select Class="mySelect">
    <option value="apple" name="Select">Apple</option>
    <option value="orange" name="Select">Orange</option>
    <option value="pineapple" name="Select">Pineapple</option>
    <option value="banana" name="Select">Banana</option>
 </select>

Display value

Upvotes: 0

djna
djna

Reputation: 55937

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.

Upvotes: 3

pjdanfor
pjdanfor

Reputation: 346

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")[0].length; or some variation of that.

Upvotes: 0

Related Questions