Home >Web Front-end >JS Tutorial >How Can I Get a Plain DOM Element from a jQuery Selector?
Retrieving DOM Elements from jQuery Selectors
Finding a straightforward way to obtain a DOM element from a jQuery selector can be a challenge. Suppose you have the following code:
<input type="checkbox" id="bob" /> var checkbox = $("#bob").click(function() { //some code });
To determine the checked value of the checkbox, you might attempt something like this:
if (checkbox.eq(0).SomeMethodToGetARealDomElement().checked) //do something.
However, this approach may not always be desirable. A simpler method exists:
$("table").get(0);
Alternatively, you can use the following shortcut:
$("table")[0];
Although accessing the raw DOM element is not frequently necessary, it may be required in certain situations. For example, consider numbering a group of checkboxes:
$(":checkbox").each(function(i, elem) { $(elem).data("index", i); }); $(":checkbox").click(function() { if ($(this).is(":checked") && $(this).data("index") == 0) { // do stuff } });
The above is the detailed content of How Can I Get a Plain DOM Element from a jQuery Selector?. For more information, please follow other related articles on the PHP Chinese website!