Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

javascript - jQuery object and DOM element

I would like to understand relationship between jQuery object and DOM element..

When jQuery returns an element it shows up as [object Object] in an alert. When getElementByID returns an element it shows up as [object HTMLDivElement]. What does that mean exactly? I mean are both of them objects with a difference ?

Also what methods can operate on jQuery object vs DOM element? Can a single jQuery object represent multiple DOM elements ?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I would like to understand relationship between jQuery object and DOM element

A jQuery object is an array-like object that contains DOM element(s). A jQuery object can contain multiple DOM elements depending on the selector you use.

Also what methods can operate on jQuery object vs DOM element? Can a single jQuery object represent multiple DOM elements ?

jQuery functions (a full list is on the website) operate on jQuery objects and not on DOM elements. You can access the DOM elements inside a jQuery function using .get() or accessing the element at the desired index directly:

$("selector")[0] // Accesses the first DOM element in this jQuery object
$("selector").get(0) // Equivalent to the code above
$("selector").get() // Retrieve a true array of DOM elements matched by this selector

In other words, the following should get you the same result:

<div id="foo"></div>

alert($("#foo")[0]);
alert($("#foo").get(0));
alert(document.getElementById("foo"));

For more information on the jQuery object, see the documentation. Also check out the documentation for .get()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...