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 can I get the ID of an DOM element using jQuery?
In jQuery, the attr() method is used to get the id attribute of the first matching element. This method allows you to retrieve any attribute value from a DOM element.
Syntax
The basic syntax to get an element's ID using jQuery is ?
$(selector).attr("id")
Where selector is the jQuery selector that identifies the element whose ID you want to retrieve.
Example
Here's a complete example that demonstrates how to get the ID of a DOM element when a button is clicked ?
<html>
<head>
<title>Getting DOM Element ID with jQuery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#btn1').click(function () {
alert($('#test').attr('id'));
});
});
</script>
</head>
<body>
<div id="test">
This is a test div element
</div>
<button type="button" id="btn1">Click Here to Get ID</button>
</body>
</html>
In this example:
- We have a
<div>element withid="test" - When the button is clicked, the jQuery code
$('#test').attr('id')retrieves the ID of the div - The retrieved ID is displayed in an alert box
The output when you click the button will be ?
test
Alternative Method
You can also use the prop() method to get the ID attribute ?
$('#test').prop('id')
Both attr('id') and prop('id') will return the same result for getting element IDs.
Conclusion
Using jQuery's attr('id') method is the most common and straightforward way to retrieve the ID of any DOM element. This method is particularly useful when you need to dynamically work with element IDs in your JavaScript code.
