Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 692
Hommer Smith Avatar asked Dec 11 '22 10:12

Hommer Smith


1 Answers

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/

like image 195
jfriend00 Avatar answered Jan 05 '23 01:01

jfriend00