Home  >  Article  >  Web Front-end  >  How Can I Get a Plain DOM Element from a jQuery Selector?

How Can I Get a Plain DOM Element from a jQuery Selector?

DDD
DDDOriginal
2024-10-30 19:09:02924browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn