jQuery Get the Id of the Current Element

Useful Tips

Sometimes is really useful not only to read the docs, but to be aware of what the community is writing. Although you get familiar with a library or framework, it happens sometimes to discover very very useful things in them, kind of snippets, that you’ve missed all the time.

In that sense, I’m going to talk about something really small as code in jQuery, but that is quite used. The id selector.

It just so happens that after you discover the selection of an attribute with .attr() method you start selecting even the ids with it.

$('element').attr('id');

Which of course works quite well, but there is a built-in method that has clearer syntax and … better performance – the id.

Think of something like that:

$('element').click(function() {
    alert($(this).attr('id'));
}

It can be replaced with:

$('element').click(function() {
    alert($(this).id);
}

It’s cool!

12 thoughts on “jQuery Get the Id of the Current Element

  1. of course, if you dont have the raw node, your technique is good, eg:

    $(‘ul li:first’).id;

    Though you can also access the raw node;

    $(‘ul li’)[0].id;

  2. This is actually how we got the ids of elements way back when before the days of jQuery, when people actually had to know javascript!

  3. Just to reply to all comments, of course I know there’s a “pure” javascript approach and naturally the jQuery’s solution derive from that. Actually if you’d like to access an attribute for a particular element you can use the same notation:

    var element = document.getElementById(‘element_id’);
    alert(element.id);

    What jQuery is doing is practically the same, while I was trying the show that sometimes we make it the hard way with $(element).attr() method, which is slow and the notation is not so elegant.

    The same happens when you try to access the title, src or whatever attribute you’d like.

    best regards,
    stoimen

  4. It’s not work in 1.4.2:

    $(function(){
    alert( $(“#zz”).id);
    });

    ajsiojqijowis
    result is ‘undefined’.

  5. $(‘element’).click(function() {
    alert($(this).attr(‘id’));
    }
    above code not workin.

    pls help how to get current element value.

Leave a Reply

Your email address will not be published. Required fields are marked *