197

I'm having an impossibly hard time finding out to get the actual DOMElement from a jQuery selector.

Sample Code:

<input type="checkbox" id="bob" />
var checkbox = $("#bob").click(function() { //some code  } )

and in another piece of code I'm trying to determine the checked value of the checkbox.

  if ( checkbox.eq(0).SomeMethodToGetARealDomElement().checked )
    //do something.

And please, I do not want to do:

  if ( checkbox.eq(0).is(":checked"))
    //do something

That gets me around the checkbox, but other times I've needed the real DOMElement.

informatik01
  • 16,038
  • 10
  • 74
  • 104
BillRob
  • 4,659
  • 4
  • 26
  • 38
  • 4
    One case in which this may be needed: in Knockout.js the function `applyBindings` expects a DOM node not a jQuery selector. This question (and its answers) are exactly what is needed. – Muhammad Alkarouri Apr 14 '13 at 12:09

4 Answers4

291

You can access the raw DOM element with:

$("table").get(0);

or more simply:

$("table")[0];

There isn't actually a lot you need this for however (in my experience). Take your checkbox example:

$(":checkbox").click(function() {
  if ($(this).is(":checked")) {
    // do stuff
  }
});

is more "jquery'ish" and (imho) more concise. What if you wanted to number them?

$(":checkbox").each(function(i, elem) {
  $(elem).data("index", i);
});
$(":checkbox").click(function() {
  if ($(this).is(":checked") && $(this).data("index") == 0) {
    // do stuff
  }
});

Some of these features also help mask differences in browsers too. Some attributes can be different. The classic example is AJAX calls. To do this properly in raw Javascript has about 7 fallback cases for XmlHttpRequest.

Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
cletus
  • 616,129
  • 168
  • 910
  • 942
  • 1
    Thanks, but the get method still returns a jquery element, not the dom element. Otherwise the .checked property call would have worked. – BillRob Nov 05 '09 at 02:15
  • Try `$('a').get(0).nodeType==1` in Firebug on this page, does it evaluate to true or fail? – meder omuraliev Nov 05 '09 at 02:20
  • @BillRob if get() isn't returning the DOM element, something is wrong. See the docs here: http://docs.jquery.com/Core/get#index – Sixten Otto Nov 05 '09 at 02:27
  • `$('').appendTo('body').get(0).checked` – meder omuraliev Nov 05 '09 at 02:29
  • Thanks Steve, cletus, the jquery documentation is very confusion around the .get operator. I found an article that mentioned it was deprecated and don't get confused with the jQuery.get() ajax method. The core issue is I have many years of javascript libraries I've built up and I can't rewrite all of them instantly, so they get converted as time permits. – BillRob Nov 05 '09 at 02:39
  • `if ($(this).is(":checked")) {` is insane. That's who knows how many function calls and who know what logic versus one look-up against a boolean property (`checked`) of the DOM element that works in every single browser since 1996. – Tim Down Nov 05 '09 at 10:19
  • 5
    What's the point of using jQuery if you're going to be explicitly using DOM properties? Shouldn't it be better to have consistent code that's error-proof against possible TypeErrors? A few years ago I used to be an elitist ECMAScripter and avoided frameworks but the more I learned about inconsistencies I ended up relying more. Browser engines are only getting faster and faster, unless the speed is noticeable you shouldn't really worry about this. The entire point of using a framework is to have workable consistent code solving many issues, not doing stuff as fast as possible. – meder omuraliev Nov 05 '09 at 17:51
  • TypeErrors won't be a problem if you know which nodes in the DOM you're targetting. If you don't, your intentions are vague and your code will be error-prone, which is precisely what slavish adherence to doing everything the jQuery way seems to lead to, judging by the questions and answers jQuery users provide on SO and other forums. Using both jQuery and DOM properties/methods is no problem: jQuery by its very nature cannot force a particular way of doing things, and being unafraid to deal with the DOM directly is not going make anyone a worse developer. – Tim Down Nov 06 '09 at 01:09
  • Now if only the .get(0) worked in IE7 and earlier versions.... It's fine in normal browsers, but returns undefined in IE7. – Slavo Feb 09 '10 at 09:38
  • @Slavo .. `get(0)` should work fine in IE7. Please post your problem as a question? – meder omuraliev Jul 29 '10 at 05:52
  • An example where this is needed is for passing a DOM node as a parameter to a function, such as [`MutationObserver.observe()`](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/observe). – mbomb007 Apr 30 '19 at 18:43
  • With this solution, keep in mind that jquery returns an array-like object of multiple items. So for instance if you've got multiple tables, `$("table")` will return all of them, so you'd need to handle that appropriately. `Array.from` came in handy for me. – dkniffin Sep 03 '20 at 14:46
  • @SixtenOtto - That link doesn't seem to work anymore - I think this is the link you should be referring to now (11 years later): https://api.jquery.com/get/#get-index – ArtOfWarfare Dec 21 '20 at 00:20
8

Edit: seems I was wrong in assuming you could not get the element. As others have posted here, you can get it with:

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

I have verified this actually returns the DOM element that was matched.

eduncan911
  • 17,165
  • 13
  • 68
  • 104
6

I needed to get the element as a string.

jQuery("#bob").get(0).outerHTML;

Which will give you something like:

<input type="text" id="bob" value="hello world" />

...as a string rather than a DOM element.

Chad Hedgcock
  • 11,125
  • 3
  • 36
  • 44
1

If you need to interact directly with the DOM element, why not just use document.getElementById since, if you are trying to interact with a specific element you will probably know the id, as assuming that the classname is on only one element or some other option tends to be risky.

But, I tend to agree with the others, that in most cases you should learn to do what you need using what jQuery gives you, as it is very flexible.

UPDATE: Based on a comment: Here is a post with a nice explanation: http://www.mail-archive.com/jquery-en@googlegroups.com/msg04461.html

$(this).attr("checked") ? $(this).val() : 0

This will return the value if it's checked, or 0 if it's not.

$(this).val() is just reaching into the dom and getting the attribute "value" of the element, whether or not it's checked.

James Black
  • 41,583
  • 10
  • 86
  • 166
  • 2
    I could use document.getElementById or the MS ajax $get method. Since MS endorsed jquery I'm trying to break my reliance on ms ajax javascript and learn jquery. It seems entirely counter-intuitive that jquery would change the behavior of the checkbox .val() method. As every other .val() call returns the form post fields. jQuery has been so good to work with so it was confusing to change the val() method and was hoping to find a quick workaround. – BillRob Nov 05 '09 at 02:19
  • 2
    So check out this page: http://www.mail-archive.com/jquery-en@googlegroups.com/msg04461.html – James Black Nov 05 '09 at 02:21
  • 2
    That's odd James that the val() method is really .attr("value"). I wonder why they have two different methods for it. To me .val() is the value of the form post field. – BillRob Nov 05 '09 at 02:41
  • 2
    @BillRob - jQuery is just simplifying, and standardizing, how to get the value, rather than you having to go to the actual element and do it yourself. – James Black Nov 05 '09 at 02:44
  • Sometimes you need a complex selector with IDs and a parent-child scenario and you can get it through jQuery with one line of code, but would take a day to use document.getElementById. I agree that mixing libraries is a bad idea, but it just happens sometimes and the task of getting a DOM element from a jquery object is just hard, especially with .get(0) not having browser compatibility. – Slavo Feb 09 '10 at 09:40