Organizational Research By

Surprising Reserch Topic

how to get a dom element from a jquery selector


how to get a dom element from a jquery selector  using -'javascript,jquery,dom'

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.
    

asked Sep 22, 2015 by santosh soni
0 votes
25 views



Related Hot Questions

4 Answers

0 votes

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.

answered Sep 22, 2015 by bhavin
0 votes

I needed to get the element as a string.

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

Which will give you something like:


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

answered Sep 22, 2015 by rajeshujade
0 votes

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.

answered Sep 22, 2015 by mca.agarwal
0 votes

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.

answered Sep 22, 2015 by vimaldas2005

...