Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery returns a list using id selector

I'm having trouble with jquery and selectors using the following code:

<div id="test"></div>
console.log($('#test'));

This always returns a list like [<div id=​"test">​</div>​] instead of the single element.

This results on always having to write $('#test')[0] for every operations instead of only $('#test'). Any idea on why?

Regards

like image 796
tiagoboldt Avatar asked Feb 28 '11 10:02

tiagoboldt


People also ask

Does jQuery selector return an array?

The jQuery selector code returns an array by itself.

What is ID selector jQuery?

The #id Selector The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.

What does $() return in jQuery?

jQuery() Return a collection of matched elements either found in the DOM based on passed argument(s) or created by passing an HTML string.


1 Answers

Jquery will not return the HtmlElement, it returns a jQuery object.

A jQuery object contains a collection of Document Object Model (DOM) elements that have been created from an HTML string or selected from a document. Since jQuery methods often use CSS selectors to match elements from a document, the set of elements in a jQuery object is often called a set of "matched elements" or "selected elements"

The jQuery object itself behaves much like an array; it has a length property and the elements in the object can be accessed by their numeric indices [0] to [length-1]. Note that a jQuery object is not actually a Javascript Array object, so it does not have all the methods of a true Array object such as join(). http://api.jquery.com/Types/#jQuery

This is an example of the Composite Design Pattern

The Composite Pattern describes a group of objects that can be treated in the same way a single instance of an object can. Implementing this pattern allows you to treat both individual objects and compositions in a uniform manner. In jQuery, when we're accessing or performing actions on a single DOM element or a group of DOM elements, we can treat both in a uniform manner. http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#designpatternsjquery

like image 127
Greg Avatar answered Oct 20 '22 04:10

Greg