问题描述:

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"
相关阅读:
Top