Home > Web Front-end > JS Tutorial > 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
Release: 2024-10-30 19:09:02
Original
999 people have browsed it

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 });
Copy after login

To determine the checked value of the checkbox, you might attempt something like this:

if (checkbox.eq(0).SomeMethodToGetARealDomElement().checked)
    //do something.
Copy after login

However, this approach may not always be desirable. A simpler method exists:

$("table").get(0);
Copy after login

Alternatively, you can use the following shortcut:

$("table")[0];
Copy after login

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
  }
});
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template