views:

92

answers:

4
document.getElementById("main").src = '02.jpg';

works

but

$('#main').src = '02.jpg';

doesn't

+9  A: 
$("#main").attr("src", "02.jpg");
Mike Robinson
+7  A: 

$('#main') returns a jQuery object, not a HTMLElement, therefore no src property is defined on the jQuery object. You may find this article useful.

Mike has shown one way of setting the src attribute (the way he has shown could probably be considered the most jQuery like way of doing it). A couple of other ways

$("#main")[0].src = '02.jpg';

or

$("#main").get(0).src = '02.jpg';
Russ Cam
In addition to returning an object, you can treat that object as an array, as in this answer, and reference it as such.
+1  A: 

$('#main').src = '02.jpg';

The jQuery wrapper you get from $(...) does not reproduce all properties and methods of the DOM object(s) it wraps. You have to stick to jQuery-specific methods on the wrapper object: in this case attr as detailed by Mike.

The ‘prototype’ library, in contrast to jQuery, augments existing DOM objects rather than wrapping them. So you get the old methods and properties like .src in addition to the new ones. There are advantages and drawbacks to both approaches.

bobince
Does exposing the DOM objects directly increase the risk of having browser compatibility issues? I assume by using a JQuery method such as .attr(), we can be more comfortable it will run with all browsers.
Russell
It's a myth that jQuery solves *all* browser issues; such a thing isn't possible, really. `attr` has a couple of fixups for specific corner cases but other than that it's just the same as using DOM property access (only with slightly different property names to match the attribute names; however it is *not* implementing attribute access). You can certainly still experience browser compatibility issues with `attr`.
bobince
A: 

$("#main") is a collection of matches from a search. document.getElementById("main") is a single DOM element - that does have the src property. Use the attr(x,y) method for when you want to set some attribute on all of the elements in the collection that gets returned by $(x), even if that is only a single element as in getElementById(x).

It's akin to the difference between int and int[] - very different beasts!

Andrew Matthews