How to get a DOM Element from a jQuery selector? How to get a DOM Element from a jQuery selector? jquery jquery

How to get a DOM Element from a jQuery selector?


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.


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.


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.