Get the ID of an Element using jQuery
The ID property of the element interface represents the element's identifier, reflecting the ID global attribute. It must be unique in a document. $('selector').attr('id') will return the id of the first matched element.ID Selector
<div id="test"></div>
$(document).ready(function() {
alert($('#test').attr('id'));
});
Class Selector
If you want to get an ID of an element, let's say by a class selector, when an event was fired on that specific element, then the following will do the job:
$('.your-class-selector').click(function(){
alert($(this).attr('id'));
});
More than one element ID
If your matched set contains more than one element, you can use the conventional .each loop to return an array containing each of the ids:
var ids = []
$('selector').each(function(){
ids.push($(this).attr('id'))
})
return ids

Div-1
Div-2
Div-3
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn").click(function(){
var ids = [];
$(".myDiv").each(function(){
ids .push($(this).attr("id"));
});
alert(ids .join(", "));
});
});
</script>
</head>
<body>
<div class="myDiv" id="ID-1">Div-1</div>
<div class="myDiv" id="ID-2">Div-2</div>
<div class="myDiv" id="ID-3">Div-3</div><br>
<button type="button" id="btn">Show IDs</button>
</body>
</html>
ID Selector ("#id")

The ID is a property of an HTML Element. However, when you write $("#something"), it returns a jQuery object that wraps the matching DOM element(s). To get the first matching DOM element back, call get(0).
$("#test").get(0)
On this native element, you can call id, or any other native DOM property or function.
$("#test").get(0).id
Or
$('#test')[0].id;
Related Topics
- How to get input textbox value using jQuery
- Get Selected Dropdown Value on Change Event | jQuery
- How to submit a form using ajax in jQuery
- Open Bootstrap modal window on Button Click Using jQuery
- How to select an element with its name attribute | jQuery
- How to get the data-id attribute using jQuery
- How to disable/enable submit button after clicked | jQuery
- How to replace innerHTML of a div using jQuery
- Change the selected value of a drop-down list using jQuery
- How to get the value of a CheckBox with jQuery
- How to wait 'X' seconds with jQuery?
- How to detect enter key press on keyboard | jQuery
- How to allow numbers only in a Text Box using jQuery.
- How to dynamically create a div in jQuery?