I am trying to access href
attribute of HTML <a>
element but somehow that value gets changed automatically.
Following is my code :
function getTDElement(anchorString)
{
var td = document.createElement('td');
// i think this is not a good way to add child to html element but
// i have to do it for some unavoidable reason
td.innerHTML = anchorString;
var anchor = td.firstChild;
// following line prints url like
// http://localhost/myservlet?myParam=foobar
console.log(anchor.href);
return td;
}
// im passing only /myservlet?myParam=foobar in following line
getTDElement("<a href=/myservlet?myParam=foobar>display</a>");
I am not able to understand why and how href attribute of element changes automatically.
Can anyone please shed some light on this issue?
The href
property on a link element is a special property, not a simple string. It is liable to change your href value to the absolute URL it thinks it resolves to. You can get the unchanged value using getAttribute
.
console.log(anchor.getAttribute('href'));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.