Getting the base element from a jQuery object

Jquery

Jquery Problem Overview


I'm struggling to find the right terminology here, but if you have jQuery object...

$('#MyObject')

...is it possible to extract the base element? Meaning, the equivalent of this:

document.getElementById('MyObject')

Jquery Solutions


Solution 1 - Jquery

$('#MyObject').get(0);

I think that's what you want. I think you can also reference it like a regular array with:

$('#MyObject')[0];

But I'm not sure if that will always work. Stick with the first syntax.

Solution 2 - Jquery

Yes, use .get(index). According to the documentation:

> The .get() method grants access to the DOM nodes underlying each jQuery object.

Solution 3 - Jquery

A jQuery object is a set of elements. In your case, a set of one element. This differs from certain other libraries, which wrap single elements and provide alternate syntax for selectors that return multiple matches.

Aaron W and VolkerK already explained how to access the first (index 0) element in the set.

Solution 4 - Jquery

I tested Aaron's statements on all the browsers I have available on my box:

$('#MyObject').get(0);

vs

$('#MyObject')[0];

As far as I can tell, it is only a matter of personal preference.

Functionally, both these statements are equivalent for both existing and non-existing elements. I tested the following browsers: Chrome 27.0, FF 21.0, IE10, IE9, IE8, IE7, IE6.

In the speed tests that I ran, it was not always possible to tell which variation was faster; the outcome was not always consistent, even on the same browser. For the speed tests, I only tested existing elements. My test results are here.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondansaysView Question on Stackoverflow
Solution 1 - JqueryAaron WagnerView Answer on Stackoverflow
Solution 2 - JqueryVolkerKView Answer on Stackoverflow
Solution 3 - JqueryShog9View Answer on Stackoverflow
Solution 4 - JqueryVeeTheSecondView Answer on Stackoverflow