16

Simple question:

How do I refer to self without using $.each() for example when I want to set html() to own attribute?

$('*[rel]').html($(this).attr('rel')); // nope $('*[rel]').html($(self).attr('rel')); // nah $('*[rel]').html($(sender).attr('rel')); // undefined $('*[rel]').html($(target).attr('rel')); // still undefined $('*[rel]').html($(???).attr('rel')); // this isn't even correct syntax $('*[rel]').html($(beer).attr('rel')); // well that would be tasty $('*[rel]').html($(woman).attr('rel')); // not in this life $('*[rel]').html($(god help me!).attr('rel')); // He probably doesn't even know how to use a computer $('*[rel]').html($(i give up).attr('rel')); // unexpected... o'rly? 
2
  • 5
    He probably doesn't even know how to use a computer :) Commented Sep 16, 2013 at 18:07
  • 3
    Vote up for the question itself, if only for the humor in it... :) Commented Oct 13, 2016 at 9:43

1 Answer 1

18

You can pass a function instead of a a string.

$('[rel]').html(function() { return $(this).attr('rel'); }); 

The reason why all of your examples don't work is because in each case your code executes long before the selector has been evaluated. This is something you really need to understand - it's even more relevant when callbacks are involved e.g. for AJAX or timers: When you put code somewhere it's executed at this point. So foo(some code here) will always execute the code that's part of the function argument no matter what foo does. The only reason to avoid this is passing a function that contains this code - that was the function expression is evaluated (which evaluates to a callable function). Then the actual function (which obviously needs to expect a callable instead of a simple value) can invoke the passed function whenever it's appropriate.

Sign up to request clarification or add additional context in comments.

2 Comments

Ok. I do understand that js is based on callbacks, but was sure that long, long ago, in a land far, far away, there lived a beautiful young girl... yes, and she had computer in which on old, old version of j, j, jQuery sender or self worked. But I may be wrong about the girl, when I was young every girl was beautiful.
Yeah I think that girl made you think weird things - it's technically impossible that what you suggested ever worked that way.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.