Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the object's id?

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>
like image 911
Hao Avatar asked Apr 26 '11 11:04

Hao


2 Answers

Use attr() to read attributes:

alert($('#hola').attr('id'));
like image 67
Joachim Sauer Avatar answered Oct 02 '22 20:10

Joachim Sauer


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.

like image 44
Andy E Avatar answered Oct 02 '22 21:10

Andy E