1

I am reading an excellent book about jQuery (Apress Pro jQuery) and I am a little confused about the use of 'this'. For example I am reading the following code :

<script type="text/javascript">
$(document).ready(function() {
 var isResult = $('img').is(function(index) {
 return this.getAttribute("src") == "rose.png";
 });
 console.log("Result: " + isResult);
 });
</script>

I am wondering at which object in this case 'this' refers to. Thank you.

asked May 4, 2012 at 19:22
7
  • 1
    It's reffering to the selector $('img') Commented May 4, 2012 at 19:23
  • 2
    If you want to check it out, you can always open up a console and do console.log(this) to see what it's referring to. Commented May 4, 2012 at 19:24
  • 3
    @RPM, 'this' is not referencing the jQuery object $('img'), it is referencing the DOM element. Commented May 4, 2012 at 19:26
  • @BrianGlaz Unless you have break point inside that function, console.log(this) would return window object. Commented May 4, 2012 at 19:28
  • @Vega I meant 'open up a console' so you can view the result. I didn't mean to execute that code from the console. It should be inside the function, of course. Sorry if that wasn't clear. Commented May 4, 2012 at 19:30

1 Answer 1

5

this in the "this" context is a reference to the DOM img element.

answered May 4, 2012 at 19:24
Sign up to request clarification or add additional context in comments.

4 Comments

it's actually the set of objects referred to by the selector, which may contain 0 or more img elements.
@SamTyson: Actually, the function is ran for each <img> element, so this the individual <img> element.
@SamTyson : Great answer too, the console.log(this) that I used inside the function returned six elements with one of them only with src="rose.png" attribute so the final result of the second console command is true!
As the book says is(function(index)) --> Returns true if the function returns true at least once.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.