问题
anchorobject = document.getElementById('backbutton');
alert(anchorobject);
<a href="http://www.hotmail.com" id="backbutton">back</a>
The above code alerts the href attribute string (http://www.hotmail.com
). Not the object itself. The file I am editing is just a local file which I want to use in some third party program in the future. First, I am coding it on my local computer. When I try to get the object of a DIV
it works just fine.
Why can't I get the object of an anchor (<a>
) tag in JavaScript using document.getElementById()
?
回答1:
You are getting the anchor object. It's just that alert
is a very poor debugging solution. If you alert an anchor object, it will just show you it's href
. See this example. Instead, I would recommend using Firebug or Chrome with console.log
.
回答2:
How about this?
alert(anchorobject.getAttribute("href"));
回答3:
The anchorobject
is your actuall anchor object, but if you use it as a string (in your case with an alert()
), the object's toString()
method creates a string from the href
tag.
来源:https://stackoverflow.com/questions/7162211/getting-object-of-anchor-tag-using-getelementbyid