9

Random just out of curiosity question:

Let's say for whatever reason I get an element back from a function

$(element)

But I want to remove the $( __ ) jQuery wrapper to leave the regular DOM Element:

element

Is this possible? (I'm sure it'd be smart to test $(element).length() to make sure it isn't more than 1 thing inside beforehand too...

jsFiddle

Mark Pieszak - Trilon.io
  • 61,391
  • 14
  • 82
  • 96

3 Answers3

21
var firstElem = $(element)[0];

or

var firstElem = $(element).get(0);

Calling get() without an index gives you an array of the elements.

Reference: jQuery get()

epascarello
  • 204,599
  • 20
  • 195
  • 236
  • Sad, I knew about just doing `$(element)[0]` too haha... thank god it's friday I need a break haha. Any reason to use `.get()` over `.toArray()`, or vice versa? – Mark Pieszak - Trilon.io Sep 28 '12 at 15:00
  • @mcpDESIGNS: Just to be clear, I don't think epascarello is actually suggesting the form of `$(element)[0]`, which makes no sense to use. You'd only need `[0]` or `.get(0)` when you've been given a previously constructed jQuery object. – I Hate Lazy Sep 28 '12 at 15:08
  • Yeah I know you guys meant that you can break it down by `[0]` the first element. Appreciate it fellas! – Mark Pieszak - Trilon.io Sep 28 '12 at 15:10
  • @mcpDESIGNS: The `.get()` method lets you grab an element at a particular index. If you don't provide an index, it returns an Array of all the elements. The `.toArray()` method only returns an Array. So `x[0]` is equivalent to `x.get(0)` and `x.toArray()` is equivalent to `x.get()`. Advantage `toArray()` has is its meaningful name. Advantage `[0]` has is that it avoids the function call. – I Hate Lazy Sep 28 '12 at 15:14
6

DOM elements are stored as properties at numeric zero-based indices, so you access them just like you would for any other object.

$jqObj[0];

Or get a full Array of elements using toArray()

$jqObj.toArray();
I Hate Lazy
  • 47,415
  • 13
  • 86
  • 77
0

Fiddle: http://jsfiddle.net/xHj5d/2/

removeJWrapper($('#ohHeyo'));

function removeJWrapper (el) {
    console.log(el[0]);
}
NullUserException
  • 83,810
  • 28
  • 209
  • 234
thingEvery
  • 3,368
  • 1
  • 19
  • 25