5

How to get the id on an object, i know the id is hola, but i need to get it during runtime

alert($('#hola').id);

The idea is this:

<script>

    (function ($) {

    $.fn.hello = function(msg) {
        alert('message ' + msg);
        alert('is from ' + this.id); // this.id doesn't work
    };

    })(jQuery);


    $('#hola').hello('yo');

</script>
Hao
  • 8,047
  • 18
  • 63
  • 92
  • 1
    Inside a jQuery plugin, `this` refers to the jQuery object that represents the selected elements. In this case using `this.attr('id')` as @Joachim posted, is probably the easiest way (and `$('#hola').id` does not work btw). – Felix Kling Apr 26 '11 at 11:58

3 Answers3

12

Use attr() to read attributes:

alert($('#hola').attr('id'));
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
9

The most efficient approach would be:

this[0].id

this.attr("id") takes longer to achieve the same thing because many checks are made and different codepaths are followed based on the parameter passed. Depending on how often you call the function, there could be a significant difference on, say, a mobile browser with a slow processor.

You can read more about this here.

Andy E
  • 338,112
  • 86
  • 474
  • 445
  • 1
    +1 although it has to be checked whether `this` contains elements or not. – Felix Kling Apr 26 '11 at 12:08
  • 1
    @Felix: yeah, that's good to point out. `typeof this[0] == "object" && this[0].id` should be sufficient to prevent an error when `this[0]` is undefined or not an object. – Andy E Apr 26 '11 at 12:10
5

You can read it as atttibute:

alert($('#hola').attr('id'));
Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208