How to get a DOM Element from a JQuery Selector

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.



You can access the raw DOM element with:


or more simply:


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.


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


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


I needed to get the element as a string.


Which will give you something like:

<input type="text" id="bob" value="hello world" /> a string rather than a DOM element.


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:[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.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.