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:
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'
);
}
}
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:
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';
}
This code distinguishes between DOM nodes and elements, addressing potential differences in browser implementations.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3