Reputation: 20203
with dom elements, how can I get the object type?
the only clue I can see is the
method using the same name. promisingly, it has an inheritance _
proto_
as well._
proto_
excepting IE, is this the right path to follow?
if so, what would
function getNodeType( node ) return string
// would return HTMLLIElement for example
function isNodeType( node, type ) return boolean
// whether node is or is inherited from that type
would look like?
Upvotes: 1
Views: 1724
Reputation: 19134
instanceof
should be fine if you are only dealing with one document. If you are testing objects from another frame, then instanceof
won't work:
document.body instanceof HTMLBodyElement // true
var iframe = document.body.appendChild(document.createElement('iframe'));
iframe.contentDocument.body instanceof HTMLBodyElement // false!
Instead, you have to do string comparisons. This is what Google Closure ended up doing to implement goog.isArray
(before Array.isArray([])
was invented). For example:
iframe.contentDocument.body.toString() === '[object HTMLBodyElement]' // true
But I would recommend just using tagName
or nodeName
.
Upvotes: 4
Reputation: 35700
function isNodeType( node, type ){
return node instanceof type;
}
function getNodeType(node){
return node.__proto__;
}
var div = document.createElement("div");
isNodeType(div, HTMLDivElement); // true
getNodeType(div); // HTMLDivElement
Upvotes: 1
Reputation: 91467
Does this give you what you want?
el.tagName;
Or, look at the instanceof
operator.
Upvotes: 2