codingbiz
codingbiz

Reputation: 26386

JQuery ID Selector -what's this behaviour

According to jQuery documentation

ID Selector

Description: Selects a single element with the given id attribute.

When you have this markup

<div id="mydiv"></div>

And you do

alert($('#mydiv')); // displays "[Object]"

alert($('#mydiv')[0]); // displays "[HTMLDivElement]"

Since we expect 1 element, what is the explanation for the array notation? What makes the two different?

NOTE: Am more concerned about why we have array/collection of DIV when we only expected one.

Is [Object] = Array {HTMLDivElement}. What is the structure of [Object]?

Upvotes: 0

Views: 137

Answers (3)

Kevin
Kevin

Reputation: 222

jQuery wraps selectors in collections. In your case you are using an ID. But when you use a class, multiple references may occur. Keep in mind that this is done to be consistent in all cases.

Upvotes: 1

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

$('#mydiv') //--> displays [Object] because it is jQuery object.

$('#mydiv')[0] // displays [HTMLDivElement] because it is a DOM element

There is a good explanation on why it is an array https://stackoverflow.com/a/7183714/297641

Upvotes: 4

alex
alex

Reputation: 490413

The [0] subscript returns a naked reference to the DOM element, not wrapped as a jQuery object.

Upvotes: 2

Related Questions