views:

510

answers:

4

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 get's me around the checkbox, but other times I've needed the real DOMElement.

A: 

That would be silly and defeat the purpose of using jQuery, but .get(0) or [0] would grab the first object in the collection if the .length is > 0.

$('a').get(0)

I suggest familiarizing yourself to a point where you don't actually need to manually invoke DOM methods unless you had no other choice to.

meder
What a great non answer. I appreciate you taking the time to point out silliness and added condescension. I will reciprocate for you and give you the same treatment.I suggest you familiarize your self with jquery as well. The .get has been deprecated because of confusion with the ajax method. The .eq method is what you should use.Any case I've needed the dom element had nothing do with invoking DOM methods, including the sample. Just accessing properties.Although I wish the table manipulation support in jquery was better.
BillRob
`.eq` returns the jqueryized object in the array.
meder
`$('a').eq(0).jquery === '1.3.2'` try this on this page.
meder
Where'd you hear about the deprecation of it?
meder
@BillRob who says that get() has been deprecated?
Sixten Otto
*fails to comprehend why someone downvoted and upvoted his comment when it was inaccurate, I admit my tone was a bit condescending and I apologize but I don't see why the downvote is needed when I was the first person with the right answer.*
meder
"manually invoking DOM methods" is not something to be avoided at all costs. In this case (checking whether a checkbox is checked) it is infinitely preferable to use a DOM property rather than the logic jQuery will apply, and much easier to understand. If you have a DOM checkbox element stored in a variable called `checkBox`, how much simpler than `checkBox.checked` can you get?
Tim Down
The advantage using jQuery is so you don't access a non existing DOM element leading into a `TypeError`. Ex: `$('dslkjffsd').get(0).checked`. You're not going to be using 99% of DOM properties which is why I suggested you don't really use them as a general tip, using jQuery in most cases would alleviate a lot of the browser inconsistencies. I know a DOM 0 propety like `.checked` wouldn't be inconsistent but I think it's better to have more consistent code that's a little more error-proof.
meder
In the case of `checked` I really would trust a direct access to the DOM property a million times more than jQuery's roundabout (and almost certainly much slower) implementation, especially if it uses the `attr()` method as has been suggested elsewhere in this question, but I do see your point. I just disagree with making dealing with the DOM directly seem so scary: it really isn't.
Tim Down
+6  A: 

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(n, i) {
  $(n).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.

cletus
Thanks, but the get method still returns a jquery element, not the dom element. Otherwise the .checked property call would have worked.
BillRob
Try `$('a').get(0).nodeType==1` in Firebug on this page, does it evaluate to true or fail?
meder
@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
`$('<input type=checkbox>').appendTo('body').get(0).checked`
meder
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
@BillRob - you're welcome.
meder
`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
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
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
Now if only the .get(0) worked in IE7 and earlier versions.... It's fine in normal browsers, but returns undefined in IE7.
Slavo
@Slavo .. `get(0)` should work fine in IE7. Please post your problem as a question?
meder
A: 

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/[email protected]/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
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
So check out this page:http://www.mail-archive.com/[email protected]/msg04461.html
James Black
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
@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
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
A: 

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
Repeating myself, but again... not in all browsers. Fails in IE7 and earlier.
Slavo