Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to get a DOM Element from a jQuery Selector?
To get a DOM Element from a jQuery Selector, use the $('#element').get(0) method. This returns the actual DOM element object, not the jQuery wrapper object.
There are two main methods to convert a jQuery object to a DOM element ?
-
.get(0)? Returns the first DOM element from the jQuery selection -
[0]? Array-style access to get the first element
Methods to Get DOM Element
Using .get(0) Method
The .get(0) method is the most common way to extract a DOM element from a jQuery object ?
// Get DOM element using .get(0)
var domElement = $('#myElement').get(0);
console.log(domElement); // Returns actual DOM element
Using Array Index [0]
You can also use array-style indexing to get the DOM element ?
// Get DOM element using array index
var domElement = $('#myElement')[0];
console.log(domElement); // Returns actual DOM element
Complete Example
Here's a practical example showing how to get a DOM element from a jQuery selector for a checkbox ?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(":checkbox").click(function() {
// Get DOM element using .get(0)
var domElement = $(this).get(0);
if ($(this).is(":checked")) {
alert("Checkbox checked! Element ID: " + domElement.id);
console.log("DOM Element:", domElement);
}
});
});
</script>
</head>
<body>
<input type="checkbox" id="demo" />
<label for="demo">Click me</label>
</body>
</html>
In this example, when you click the checkbox, it will show an alert with the checkbox ID and log the actual DOM element to the console.
Conclusion
Use .get(0) or [0] to convert jQuery objects to DOM elements when you need to access native DOM properties and methods that aren't available through jQuery.
