MarkT
MarkT

Reputation: 73

How to get an ID of a specific element that matches a JQuery selector

This should be very simple, but I'm blocking on this....

Let's say, for the sake of argument, that we want to prepend() its ID to each element matching class "class_name". I thought the right way to do it would be something like:

$('.class_name').prepend($(this).attr('id'));

But it does not work. It looks like $(this) is only usable inside event callabacks. But how do I get the ID (or any other attribute) of each specific element?

Many thanks!!!

Upvotes: 3

Views: 59

Answers (2)

elclanrs
elclanrs

Reputation: 94131

Using 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 having an unwrapped text node floating around.

Upvotes: 0

Alex
Alex

Reputation: 6406

You could use .each():

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

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

Upvotes: 5

Related Questions