Monday, February 22, 2016

3 Examples to Get the Id of an Element in jQuery

As a page author, the id of an HTML element is something you should know, but there are scenarios when the page is automatically generated or may be some form elements are generated by using frameworks like JSF. In that case, what do you do if you want to find id attribute of some elements in the page programmatically? How do you find those ids using jQuery? There are several ways to solve this problem, a couple of them we'll see in this article itself.  The jQuery API provides many methods to get any attribute or property including the id of an HTML element programmatically. In this article, I am going to share three easy ways to get the id of an element using jQuery.

As a Java developer, I have benefitted immensely from using jQuery. Since I have to occasionally work with JSP to create views like tabbed GUI, tables generated by display tag and lots of client side validation and interaction, I found jQuery quite powerful and easy to use. Before jQuery, I had tried plain JavaScript and to be honest, it wasn't a pleasant experience but jQuery changed my mind and, in fact, it helped me to learn JavaScript better.

One thing which helped me to learn jQuery is the Head First jQuery book from O'Reilly. This is one of the best book for any programmer wants to learn jQuery and I highly recommend this to my readers.

How to get the ID of an HTML element using jQuery

How to get the id of an element using jQuery

In order to get id or any other HTML attribute, we need to first grab that element using the jQuery selector. Suppose, your element has a class "synthetic" then you can grab those elements by using the following jQuery:


This will return array of jQuery objects, and if you are sure that there is only one object, you can get its id as






If you want to find ids of multiple elements then you need to iterate through those array of the jQuery object using each() iterator.

That's all about how to find the id of an HTML element using jQuery programmatically. You just need to have a selector to grab the elements you want. Always remember that $() returns an array of jQuery objects, so you need to get the jQuery object using get() method or array index before getting the id attribute from it.

Further Reading
jQuery Fundamentals By Dan Wahlin
The Complete jQuery Course: From Beginner To Advanced!
Up and Running with jQuery

No comments :

Post a Comment