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

♀尐吖头ヾ 提交于 2021-02-04 16:17:06

问题


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?


回答1:


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.




回答2:


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/




回答3:


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



来源:https://stackoverflow.com/questions/19737143/difference-between-object-src-and-object-getattributesrc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!