jQuery
Web Development
Programming
JavaScript
HTML DOM

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

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Getting an element's ID in jQuery is a fundamental DOM operation needed for dynamic event handling, form processing, and DOM manipulation. jQuery provides .attr('id') and .prop('id') to retrieve the ID attribute, while vanilla JavaScript offers .id directly. Understanding when to use each approach — and when you do not need jQuery at all — is important for writing clean, performant web code.

Method 1: .attr('id')

The most common jQuery approach:

javascript
1// Get ID of a specific element
2var id = $('#myElement').attr('id');
3console.log(id); // 'myElement'
4
5// Get ID from a class-selected element
6var id = $('.my-class').attr('id');
7console.log(id); // ID of the first matching element
8
9// Get ID inside an event handler
10$('button').click(function() {
11    var id = $(this).attr('id');
12    console.log('Clicked button:', id);
13});

.attr('id') returns the value of the id attribute as a string, or undefined if the element has no ID.

Method 2: .prop('id')

.prop('id') accesses the DOM property rather than the HTML attribute:

javascript
var id = $('#myElement').prop('id');
console.log(id); // 'myElement'

For the id attribute, .attr() and .prop() return the same value in virtually all cases. The distinction matters more for boolean attributes like checked and disabled, where .prop() returns true/false while .attr() returns the attribute string.

Method 3: Vanilla JavaScript .id

You can access the DOM element directly without jQuery:

javascript
1// Direct DOM property
2var id = document.querySelector('.my-class').id;
3
4// From a jQuery object, access the underlying DOM element
5var id = $('#myElement')[0].id;
6// or
7var id = $('#myElement').get(0).id;

This is faster than .attr('id') because it avoids jQuery's attribute lookup overhead.

Getting IDs from Multiple Elements

When a selector matches multiple elements, .attr() returns only the first match. Use .each() or .map() for all elements:

javascript
1// Using .each()
2$('.item').each(function() {
3    console.log($(this).attr('id'));
4});
5
6// Using .map() to get an array of IDs
7var ids = $('.item').map(function() {
8    return this.id;
9}).get();
10console.log(ids); // ['item1', 'item2', 'item3']
11
12// Modern jQuery with arrow functions
13var ids = $('.item').map((i, el) => el.id).get();

Common Use Cases

Dynamic Event Delegation

javascript
1// Get ID of clicked element in a list
2$('ul').on('click', 'li', function() {
3    var itemId = $(this).attr('id');
4    console.log('Selected:', itemId);
5    loadItemDetails(itemId);
6});

Form Element Identification

javascript
1// Get ID of changed form field
2$('form').on('change', 'input, select', function() {
3    var fieldId = this.id;
4    var value = $(this).val();
5    console.log(fieldId + ' changed to: ' + value);
6});
javascript
1// Use button's ID to find a related panel
2$('.toggle-btn').click(function() {
3    var panelId = $(this).attr('id').replace('btn-', 'panel-');
4    $('#' + panelId).slideToggle();
5});

Checking If an Element Has an ID

javascript
1// Check for presence of ID
2var el = $('.my-class');
3
4if (el.attr('id')) {
5    console.log('Has ID:', el.attr('id'));
6} else {
7    console.log('No ID attribute');
8}
9
10// More explicit check
11if (typeof el.attr('id') !== 'undefined' && el.attr('id') !== '') {
12    console.log('Has non-empty ID');
13}

Performance Comparison

javascript
1// Fastest: vanilla JavaScript .id
2element.id;
3
4// Fast: jQuery .prop('id')
5$(element).prop('id');
6
7// Slightly slower: jQuery .attr('id')
8$(element).attr('id');

For hot loops or performance-critical code, prefer this.id over $(this).attr('id'). Inside jQuery event handlers, this already refers to the DOM element.

Common Pitfalls

  • .attr('id') on empty jQuery objects: If the selector matches nothing, .attr('id') returns undefined, not an error. Always check that the element exists before using the ID.
  • Multiple matches: .attr() on a multi-element jQuery object returns only the first element's attribute. Use .map() or .each() to get all IDs.
  • Spaces in IDs: HTML5 allows IDs to contain most characters, but IDs with spaces, dots, or brackets must be escaped in jQuery selectors: $('#my\\.id') or $("[id='my.id']").
  • Dynamically assigned IDs: If an ID is set via JavaScript after page load, .attr('id') still reads the current value. However, document.getElementById() may not find it until the next microtask in some edge cases.
  • Using this.id vs $(this).attr('id'): Inside jQuery event handlers, this is the raw DOM element. this.id is faster and simpler than wrapping in jQuery just to call .attr('id').

Summary

  • Use $(element).attr('id') for the standard jQuery approach
  • Use this.id inside event handlers for better performance (no jQuery wrapper needed)
  • Use .map((i, el) => el.id).get() to collect IDs from multiple matched elements
  • .attr('id') returns undefined if the element has no ID or the selector matched nothing
  • For modern projects, consider vanilla JavaScript element.id or document.querySelector() instead of jQuery

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.