Hommer Smith
Hommer Smith

Reputation: 27852

Difference between object.src and object.getAttribute('src')

So, here is an example HTML code:

<img src="test.png" id="test">

And here is a Javascript code:

element = document.getElementById('test');
alert(element.getAttribute('src')); --> test.png
alert(element.src); --> domain.com/test.png

Why would getAttribute not show the domain, while .src yes, it adds the domain? Where can I find the difference between the different ways of accessing attributes in a DOM object?

Upvotes: 7

Views: 4111

Answers (3)

Ry-
Ry-

Reputation: 224904

You can see the difference in the HTML specification as “permitted attributes” versus “DOM interface”.

The specific difference for URLs is described in Reflecting content attributes in IDL attributes:

If a reflecting IDL attribute is a DOMString attribute whose content attribute is defined to contain a URL, then on getting, the IDL attribute must resolve the value of the content attribute relative to the element and return the resulting absolute URL if that was successful, or the empty string otherwise; and on setting, must set the content attribute to the specified literal value. If the content attribute is absent, the IDL attribute must return the default value, if the content attribute has one, or else the empty string.

Upvotes: 6

jfriend00
jfriend00

Reputation: 707308

getAttribute() returns exactly what was in the HTML. It may be a relative URL.

.src returns a fully qualified absolute URL, even if what was in the HTML was a relative URL.

For example:

<img id="myImage" src="foo.jpg">

var img = document.getElementById("myImage");
var src1 = link.getAttribute("src")  ;    // "foo.jpg"
var src2 = link.src;                      // "http://mydomain.com/path/foo.jpg"

Or, with a link tag:

<a id="myLink" href="foo.html">

var link = document.getElementById("myLink");
var src1 = link.getAttribute("href");    // "foo.html"
var src2 = link.href;                     // "http://mydomain.com/path/foo.html"

Working demo for a link tag: http://jsfiddle.net/jfriend00/EXYjb/

Upvotes: 11

Adam B
Adam B

Reputation: 1153

getAttribute() returns the exact attribute of the DOM element. While src is the interface of the image element.

Upvotes: 0

Related Questions