ADVERTISEMENT
ADVERTISEMENT

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

In this tutorial, you'll understand how to get the text of the selected option tag?
Submitted by Pratishtha Saxena, on June 10, 2022

jQuery is a JavaScript library used to simplify HTML DOM tree traversal, event handling, etc.

To find the id of an element - we'll use the attr() method of jQuery. attr(), here means attribute if an element. It will return the attribute of the element provided as a parameter for it. The ID, here can be treated as an attribute of the element.

Syntax:

element.attr(attributeName)

The element is specified first and the attribute name (here ID) is specified which will return the id of the element.

Note: Always put the jQuery CDN link while working with jQuery.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

jQuery example for getting the ID of an element

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <title>Title</title>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
   </head>
   <body>
      <div id="firstID">This is first div. It's ID is in console.</div>
      <script>
         let first = $('#firstID');
         console.log(first.attr('id') );
      </script>
   </body>
</html>

Output:

Example: Get the ID of an element



ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.