最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Difference between object.src and object.getAttribute('src') - Stack Overflow

programmeradmin2浏览0评论

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/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?

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./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?

Share Improve this question asked Nov 1, 2013 at 23:35 Hommer SmithHommer Smith 27.9k62 gold badges176 silver badges307 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 11

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./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./path/foo.html"

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

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.

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

发布评论

评论列表(0)

  1. 暂无评论