Why would the following two codes return the same result?
var img = new Image(400,250);
$(img).attr('src','resources/images/' + i + '.jpg');
And
var img = new Image(400,250);
img.src = 'resources/images/' + i + '.jpg';
I'm not good in jQuery so I searched the web for the differences and according to my findings I expected the first code to return: resources/images/1.jpg
and the second one to return: http://localhost:8080/myApp/resources/images/1.jpg
I appreciate a clarification.
.attr('src', newSource)
and .src = newSource
are different in that one works with attributes (or more specifically, a serialization of the DOM), and the other with DOM properties.
jQuery's .attr()
setter uses .setAttribute
, that is, it works with attributes. Attribute values are plain text which you normally write in the HTML: <img src="someSource">
.
While the browser receives the HTML and parses it into DOM, the src
attribute value is resolved relatively to the document's location (or <base>
tag if any) and the resolved URI is set as the DOM image element's src
property.
The src
attribute reflects the src
property, that is, a change in the src
property value will be reflected in the src
attribute value (and the other way around as well).
The src
property always stores the resolved URI (setting it to a relative URI will implicitly resolve it according to document location/base
tag) and a change in the property will be reflected in the attribute. The same happens the other way around (setting the property updates the attribute value).
Independent of setting the attribute or the property, the resolved URI (which will be fetched from the server) will be the same. So all of this doesn't make much difference unless you have some code that tests attributes against specific values.