当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - How to check if JS object implement some DOM IDL interface?

问题描述:

Specs say that document nodes satisfy HTMLElement IDL interface. This evaluates to true:

document.querySelectorAll('a')[0] instanceof HTMLElement

Is that correct way to test (by instanceof HTMLElement)?

Seems that all DOM interfaces are defined in global object to be accessible in that expression o_0.

网友答案:

I'm not quite sure why you want to do this, but it should work in modern browsers. It won't work in IE8 or below.

If your goal is to see whether a node is an Element or a Text node or similar, the more broadly-compatible way is to use the nodeType property:

document.querySelector('a').nodeType === 1

The types are given by the DOM specs as part of the definition of the Node interface (1 = Element).

If your goal is to test whether an element is a specific type of element (HTMLAnchorElement and so on), use nodeName or (if you know it's an element) tagName. In an HTML (not XHTML) document, those are upper case tag names, e.g.

console.log(document.querySelector('a').nodeName); // "A"
分享给朋友:
您可能感兴趣的文章:
随机阅读: