I'm working on a jQuery plugin which maps URL anchors to JS functions. The plugin takes an argument which either can be a DOM element or a Location object. So I need a way to check what kind a given argument is.
I tested the following code in FF 3.6 and IE 8. The former alerts true
, the latter alerts false
. Why is this and how can I accomplish the same behavior in both browsers? Thank you!
<!DOCTYPE html>
<html>
<head>
<script>
alert(window.location instanceof Location);
</script>
</head>
<body>
</body>
</html>
EDIT: With regard to the comment under your question, it sounds like you need to test for the difference between a DOM element, and a Location object.
You'll probably be better off testing for the DOM element using the nodeType
property.
if( obj.nodeType ) {
// it was a DOM element
}
Then you can test for various properties if nodeType
wasn't found, just to be certain it is a location
object.
if( obj.nodeType ) {
// it was a DOM element
} else if( obj.hostname && obj.pathname ) {
// it was a location object
} else {
// some ERROR
}
Original answer:
This works for me in Chrome, Safari, Firefox:
Object.prototype.toString.call(window.location) == '[object Location]';
I can't test in IE right this minute, though.
This is the method noted in the ECMAScript spec Section 8.6.2 for getting the internal [[Class]]
property name.