How to get the ID of an element using jQuery

Overview

The attr method of jQuery is used to get the value of the id attribute of a DOM element.

Syntax

element.attr(attributeName)
The syntax of the attr metthod in jQuery

Parameter

attributeName: This is the string value representing the name of the attribute to be retrieved from the DOM element.

Return value

This method returns the value of the provided attribute if the DOM element contains this attribute. Otherwise, undefined is returned.

Example

Console
Using the attr method to get the id of an element.

Explanation

In the "HTML" tab:

  • Line 5: We create a div element with an id of test.
  • Line 6: We include the jQuery file.
  • Line 8: We create a variable, ele, and assign the created div element as the value.
  • Line 9: We invoke the attr method on ele with 'id' as an argument. This will retrieve the id attribute of ele. We will get test, a result that is printed on the console.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources