var a = document.querySelector("a");
console.log( a.href == a.getAttribute("href") ); //why false? (tested on chrome)
<a href="#hello">Link</a>
Why is the output false? I mean, I know .href
is returning the whole URL, while .getAttribute()
only returns the part that is actually written on the HTML, that is why result of the comparison is false. But I wonder if this is how it is suppose to be according to spec and why. Also, I wonder if this happens with any other attribute.
The reason the property is always a full URL is in the specification:
href
of typeDOMString
The absolute URI [IETF RFC 2396] of the linked resource.
The difference comes from one being an attribute (<a href="#hello">
) and the other being a property (a.href
). An attribute is equal to whatever value is set in the markup. The property is only initialized by the attribute, but can have any other ("matching") value. Setting the property overrides the attribute though, and setting the attribute again results in discrepancies:
var a = document.querySelector('a');
a.href = a.href;
alert('Setting the property: ' + a.href + ' ' + a.getAttribute('href'));
a.setAttribute('href', '#goodbye');
alert('Setting the attribute: ' + a.href + ' ' + a.getAttribute('href'));
<a href="#hello">Link</a>
Regarding other attributes, for example, the href attribute / property of the <link>
element behaves in the same manner:
alert(document.getElementById('lnk').href);
<link id="lnk" type="text/css" rel="stylesheet" href="some.css"></link>