0

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]?

codingbiz
  • 26,179
  • 8
  • 59
  • 96
  • In most of the jQuery documentation for most selector methods you read something similar to: `Accepts a string which is used to match a set of elements.` As your selectors could always return 0, 1 or more elements it makes only sense to always return a collection. The collection is a jQuery object, containing the actual references to the DOM elements. As such to get access to the DOM reference you can use `jQueryObject[0]`. Even if 0 elements are matched, by returning a 0 length array you don't get exceptions blowing up when chaining i.e: `$('#mydiv').hide()`. – Nope Sep 05 '12 at 21:53

3 Answers3

4

$('#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

Community
  • 1
  • 1
Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134
2

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

alex
  • 479,566
  • 201
  • 878
  • 984
1

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.

Kevin
  • 222
  • 1
  • 5