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
skiabox
3,51712 gold badges67 silver badges99 bronze badges
1 Answer 1
this in the "this" context is a reference to the DOM img element.
answered May 4, 2012 at 19:24
Alex
35.5k5 gold badges81 silver badges94 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
Sam Tyson
it's actually the set of objects referred to by the selector, which may contain 0 or more img elements.
gen_Eric
@SamTyson: Actually, the function is ran for each
<img> element, so this the individual <img> element.skiabox
@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!
skiabox
As the book says is(function(index)) --> Returns true if the function returns true at least once.
lang-js
$('img')console.log(this)to see what it's referring to.console.log(this)would returnwindowobject.