Home > Web Front-end > JS Tutorial > ## What\'s the Difference Between a jQuery Object and a DOM Element?

## What\'s the Difference Between a jQuery Object and a DOM Element?

Mary-Kate Olsen
Release: 2024-10-26 18:44:30
Original
379 people have browsed it

## What's the Difference Between a jQuery Object and a DOM Element?

jQuery Object and DOM Elements

The relationship between a jQuery object and a DOM element can be confusing. Let's break it down.

Object vs. DOM Element

When jQuery returns an element, it appears as "[object Object]" in an alert. Conversely, when getElementByID returns an element, it shows as "[object HTMLDivElement]." This difference in display is due to their different object types: jQuery objects are array-like objects that encapsulate DOM elements.

Methods

jQuery functions operate on jQuery objects, not DOM elements. To access DOM elements within a jQuery function, use .get() or directly index the element:

$("selector")[0] // Accesses the first DOM element in the jQuery object
$("selector").get(0) // Equivalent to the code above
$("selector").get() // Retrieve an array of DOM elements matched by the selector
Copy after login

Multiple DOM Elements

A single jQuery object can represent multiple DOM elements selected using the specified selector.

Example

Consider this HTML:

<div id="foo"></div>
Copy after login

The following lines of code demonstrate the relationship between jQuery objects and DOM elements:

alert($("#foo")[0]); // Alerts the DOM element
alert($("#foo").get(0)); // Equivalent to the code above
alert(document.getElementById("foo")); // Alerts the DOM element
Copy after login

All three lines will return the same DOM element, which is the div with the ID "foo."

For further details, refer to the jQuery documentation for more information on the jQuery object and .get().

The above is the detailed content of ## What\'s the Difference Between a jQuery Object and a DOM Element?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template