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.
jQuery() Return a collection of matched elements either found in the DOM based on passed argument(s) or created by passing an HTML string.
The jQuery function always returns a jQuery object (that is based on an array), even if there are no elements that matches the selector.
getElementById() in the JavaScript will return DOM object whereas $('#id') will return jQuery object.
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.
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With