cc young
cc young

Reputation: 20203

in javascript, how do you determine the type of an dom object, for example, HTMLLIElement or HTMLElement

with dom elements, how can I get the object type?

the only clue I can see is the _proto_ method using the same name. promisingly, it has an inheritance _proto_ as well.

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

Answers (3)

yonran
yonran

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

wong2
wong2

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

gilly3
gilly3

Reputation: 91467

Does this give you what you want?

el.tagName;

Or, look at the instanceof operator.

Upvotes: 2

Related Questions