Reputation: 73
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
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
Reputation: 6406
You could use .each()
:
$('.class_name').each(function(index, element){
$(element).prepend($(element).attr('id'));
});
Example: http://jsfiddle.net/d8Uj8/
Upvotes: 5