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!!!


source to share

2 answers

You can use .each()


$('.class_name').each(function(index, element){





Usage each()


    var id =;
    $(this).prepend('<span>' + id + '</span>');


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



All Articles