Guy
Guy

Reputation: 876

jquery selectors vs vanilla JS selectors with .length returning different results

Given the following HTML page extract.

<form>
    <select id="select">
    <option></option>
    <option></option>
    <option></option>           
    </select>
</form>

The results of a console.log(); using $("#select").length returns 1 and document.getElementById("select").length returns 3. Does anyone have any insight as to why that it? I'm looking to run a loop using the returned value, but I can't understand why it's different. Shouldn't they both return 3? Thanks!

Upvotes: 0

Views: 2562

Answers (2)

David Fleeman
David Fleeman

Reputation: 2638

For the jquery case, use: $("#select").get(0).length

This will give you the first and only select DOM element in your array list of jquery objects. This would be the same DOM element as you get with the document.getElementById("select") call.

Update: To answer comment, the .length call on the select DOM element returns the number of options in the select elements option list. The .length on the jquery list returns the number of elements matching the selector provided. $("#select").get(0) is the same object as document.getElementById("select"). $("#select") is NOT the same object -- it is a list of jquery objects, not DOM elements.

Upvotes: 1

SLaks
SLaks

Reputation: 887453

$(...) returns a jQuery object, which is an array-like object with zero or more elements.
Its length returns the number of elements in the object.

document.getElementById() returns a single DOM object, not in any array (as opposed to the plural versions like getElementsByClassName).
Coincidentally, <select> elements have a length property which returns the number of items in the <select>.
That's what you're seeing.

Upvotes: 6

Related Questions