Is an element that's passed into a function a string or an object?
If I do something like getElementById()
to get an anchor link then pass that variable into another function, would this be passed in as a string or an object?
I know it's a stupid question, but any help 开发者_开发百科would be appreciated.
The result of getElementById() is an object
It will be passed in as an object
An object. You will be able to access the properties of that <a>
tag.
foo(document.getElementById('someID'));
function foo(element) {
alert(element.href)
alert(element.innerHTML);
}
getElementById returns a DOM element. When you store it in a variable or pass it into a function as a parameter its type will not change.
typeof document.getElementById("someAnchorId") // -> "object"
document.getElementById("someAnchorId").constructor // -> "HTMLAnchorElement() [...]"
Sometimes the way you treat a variable will convert it to a string unexpectedly. For example, if you append it to a string, JavaScript will automatically .toString() your object. Perhaps this behavior is what you're encountering.
精彩评论