How to get id of a specific element that matches a jQuery selector

It should be very easy, but I'm blocking it ....

Let's say, for the sake of argument, that we want to add () its id to every element corresponding to class_name. I thought the correct way to do it would be something like this:

...

$ ('class_name') before the name ($ (this) .attr ('ID'));

But that won't work. It looks like $ (this) is only used in case of callabacks events. But how do I get the id (or any other attribute) of each specific element?

Many thanks!!!

+3


source to share


2 answers


You can use .each()

:

$('.class_name').each(function(index, element){
    $(element).prepend($(element).attr('id'));
});

      



Example: http://jsfiddle.net/d8Uj8/

+5


source


Usage each()

:

$('.class_name').each(function(){
    var id = this.id;
    $(this).prepend('<span>' + id + '</span>');
});

      



Also, it's better to wrap it in a tag instead of expanding the text node.

0


source







All Articles