Question

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.

Was it helpful?

Solution 2

.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).


More important note

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.

OTHER TIPS

The urls displayed above are both relative urls. When resolved the src attribute will be combined with a base uri to form the actual uri used to locate the image. If you want to reference the src attribute/property via Javascript use the following example to obtain the desired result:

There urls are resolved to the following:

var img = new Image(400,250); 
$(img).attr('src','resources/images/5.jpg');
$("body").append(img);

console.log($(img).attr("src"));
//prints: resources/images/5.jpg

console.log(img.src);
//prints: http://fiddle.jshell.net/_display/resources/images/5.jpg

console.log($(img).prop("src"));
//prints: http://fiddle.jshell.net/_display/resources/images/5.jpg
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top