Get the ID of an Element using jQuery

The id property within the element interface embodies the identifier associated with the element, reflecting the globally recognized ID attribute. This identifier must be distinct and singular within a given 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
run this source code Browser View
Div-1
Div-2
Div-3

Full Source | jQuery
<!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")


How can I get the ID of an DOM element using jQuery

When you employ $("#something") in jQuery, it yields a jQuery object encapsulating the corresponding DOM element(s). Should you wish to retrieve the first matched DOM element directly, you can achieve this by using the get(0) method. This technique is particularly useful when you need to work with the actual DOM element instead of the jQuery object.

$("#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;

Conclusion

When working with jQuery, obtaining the ID of an element involves using either the .attr("id") method or directly accessing the .id property. By utilizing these approaches, you can effortlessly retrieve the unique identifier assigned to an element within the DOM. Additionally, should you require the underlying DOM element itself, employing .get(0) after selecting an element with $("#something") enables direct access to the first matching element.