admin管理员组

文章数量:1287973

I have a doubt about the jQuery core. From the docs and a couple of books I get:

var obj = $("div");

Which returns a wrapper object AKA a collection of selected DOM elements with additional methods (correct me if I'm wrong). I've read the jQuery function $() returns a wrapper object, or does it really return a copy of jQuery plus a collection of wrapped elements?

I have a doubt about the jQuery core. From the docs and a couple of books I get:

var obj = $("div");

Which returns a wrapper object AKA a collection of selected DOM elements with additional methods (correct me if I'm wrong). I've read the jQuery function $() returns a wrapper object, or does it really return a copy of jQuery plus a collection of wrapped elements?

Share Improve this question edited Dec 13, 2019 at 10:21 Shayan 8673 gold badges19 silver badges35 bronze badges asked Apr 20, 2011 at 1:59 maximusmaximus 2,4375 gold badges40 silver badges56 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

It returns an instance of a jQuery object, wrapping the elements you selected with your CSS selector (in this case, a jQuery object wrapping all the divs in the document).

jQuery isn't something that is "copied" - it is behavior that is wrapped around elements in the DOM.

var jqDivs = $("div");
var jqButtons = $("button");
var jqSubmitButton = $("button#submit");

Those 3 vars reference 3 different objects. All of them implement the same jQuery behaviors, but they do it upon different elements. jqDivs.hide() would hide the divs - jqButtons.hide() would hide the buttons, and jqSubmitButton.hide() would hide only the button with id=submit.

The term "wrap" is a bit misleading to me. jQuery keeps references to elements matched by the supplied selector as numeric properties of the jQuery instance returned by the call, so:

var allTheDivs = $('div');

returns a jQuery object with references to all the divs in the document, and:

allTheDivs[0];  // or allTheDivs['0'];

is a reference to the first one. So if you then do:

allTheDivs.hide();

it calls the hide method of the jQuery instance allTheDivs which cycles over all the referenced elements and hides them. But don't try:

allTheDivs['0'].hide()

as that will try to call hide on a DOM element, which probably won't exist so will restult in an error.

本文标签: javascriptClarification of jQuery quotwrapperquot objectStack Overflow