How to Determine DOM Object Status in JavaScript
In JavaScript, differentiating between DOM (Document Object Model) objects and regular JavaScript objects is crucial for certain operations. While the traditional approach of checking for the tagName property works in most cases, it can fail in some browsers that do not enforce read-only properties.
A Comprehensive Solution
To address this issue, consider the following function:
<code class="javascript">function isElement(obj) { try { // W3 DOM2 (works for FF, Opera, and Chrome) return obj instanceof HTMLElement; } catch (e) { // Non-DOM2 browsers return ( typeof obj === 'object' && obj.nodeType === 1 && typeof obj.style === 'object' && typeof obj.ownerDocument === 'object' ); } }</code>
This code leverages W3 DOM2 for supported browsers and checks for specific properties in non-DOM2 browsers.
Additional Options
Another approach is to use the following code:
<code class="javascript">function isNode(o) { return typeof Node === 'object' ? o instanceof Node : o && typeof o === 'object' && typeof o.nodeType === 'number' && typeof o.nodeName === 'string'; } function isElement(o) { return typeof HTMLElement === 'object' ? o instanceof HTMLElement : o && typeof o === 'object' && o !== null && o.nodeType === 1 && typeof o.nodeName === 'string'; }</code>
This code distinguishes between DOM nodes and elements, addressing potential differences in browser implementations.
The above is the detailed content of How to Reliably Determine if a JavaScript Object is a DOM Element?. For more information, please follow other related articles on the PHP Chinese website!