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
  • 52,747
  • 13
  • 77
  • 93

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
  • 195,511
  • 20
  • 184
  • 225
  • 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
  • 45,169
  • 12
  • 84
  • 76
0

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

removeJWrapper($('#ohHeyo'));

function removeJWrapper (el) {
    console.log(el[0]);
}
NullUserException
  • 81,190
  • 27
  • 202
  • 228
thingEvery
  • 3,324
  • 1
  • 18
  • 25