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?
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With