Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between $(this).src and document.getElementById().src?

in a current project I am using jQuery. I was just wondering why this works,

$('#homeIcon').hover(function(){
    document.getElementById('homeIcon').src = "pic/home-icon_hover.png";
})

but this won't:

$('#homeIcon').hover(function(){
    $(this).src = "pic/home-icon_hover.png";
})

Shouldn't those methods do exactly the same?

FYI homeIcon is an <img>.

like image 486
oopbase Avatar asked May 04 '26 06:05

oopbase


1 Answers

In jquery you should do

$('#homeIcon').hover(function() {
    $(this).attr('src',"pic/home-icon_hover.png")
})

To set the value of the src attribute. from jQuery version 1.6 and up it is recommended to use prop instead of attr, so:

$('#homeIcon').hover(function() {
    $(this).prop('src',"pic/home-icon_hover.png")
})
like image 149
idanzalz Avatar answered May 06 '26 20:05

idanzalz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!