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
Explanation
In the "HTML" tab:
- Line 5: We create a
divelement with an id oftest. - Line 6: We include the jQuery file.
- Line 8: We create a variable,
ele, and assign the createddivelement as the value. - Line 9: We invoke the
attrmethod onelewith'id'as an argument. This will retrieve theidattribute ofele. We will gettest, a result that is printed on the console.