Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What object does jquery return exactly?

I've been working on my own personal JavaScript library for a while now, and it works fine. But I've been wondering about the jQuery return object.

Lets say you have a few divs in your DOM and you select them with $("div") jquery actually returns the selected nodes (as an object/array?) in the console log and you can mouse-over them to see where they are in the documents.

My object actually returns the entire object itself, so if you call kj("div") (Where kj is my object name) it shows up like this in the console log:

    > kj
    > elements: Array[10]
    > length : 10
    > more stuff

My question is, how can I make it return something like jQuery?

Thanks in advance.

like image 560
Jorik Avatar asked Mar 06 '11 04:03

Jorik


People also ask

What does the jQuery function return?

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

Does jQuery always return an array?

The jQuery function always returns a jQuery object (that is based on an array), even if there are no elements that matches the selector.

Which method returns the element as a jQuery object?

getElementById() in the JavaScript will return DOM object whereas $('#id') will return jQuery object.

Is jQuery return value?

Like the others said, jQuery returns jQuery objects in most cases, and accessing the actual object can be accomplished using an indexer [] or the get method.


2 Answers

I think what you are looking for is that in jQuery the Array of elements is the primary object, the methods and other information is connected to that array as properties.

function $$(tagname){
  var x = document.getElementsByTagName( tagname );
  x.moreStuff = true;
  return x;
}

var d = $$('div');

because typeof Array === 'object' you can arbitrarily attach methods and properties to an array.

like image 65
Gabriel Avatar answered Sep 30 '22 11:09

Gabriel


JQuery hooks up it's own references to an object whick in turn reference to things in the dom. Those references are a little more complex than just the "contents of the html" as there are events attached. JQuery also has very efficient "Selectors" that iterate over the dom and build those references.

I have to say I agree with the Scrum Meister. JQuery's an accepted standard across even Microsoft development these days (WOOHOO!). Why not use it?

like image 40
Gats Avatar answered Sep 30 '22 12:09

Gats