tags:

views:

25

answers:

2

The following code doesn't work! 'this' in in the context when i access it is the document.

$(document).ready(function(){
  $(".myclass[id]").html(this.id);
});

How do I do the above without writing an extension or plugin? Is it possible?

+1  A: 
$(".myclass[id]").each(function(){
  //this is in the right context
});
Kobi
+1  A: 

You want to put an attribute value on the innerHTML each node on a set of matched elements.

I suggest you to iterate over all the matched elements, and get the attribute you desire of each one:

$(document).ready(function(){
  $(".myclass[id]").each(function () {
    $(this).html(this.id);
    // or $(this).html($(this).attr('id'));
  });
});
CMS
**this** is different in the nested each function. **this** in the nested each anon function would be the iterated element, no longer the document.
Kevin Peno
@Kevin: Exactly, he wants an attribute value of the iterated elements.
CMS
Thanks this is a nice solution. I was doing it like this via 'jQuery.fn.extend({ ...' and then iteration over each. This is more code size efficient.
Johan