I'm trying to get:
document.createElement('div') //=> true
{tagName: 'foobar something'} //=> false
In my own scripts, I used to just use this since I never needed tagName
as a property:
if (!object.tagName) throw ...;
So for the second object, I came up with the following as a quick solution -- which mostly works. ;)
The problem is, it depends on browsers enforcing read-only properties, which not all do.
function isDOM(obj) {
var tag = obj.tagName;
try {
obj.tagName = ''; // Read-only for DOM, should throw exception
obj.tagName = tag; // Restore for normal objects
return false;
} catch (e) {
return true;
}
}
Is there a good substitute?
here's a trick using jQuery
so putting it in a function:
You could try appending it to a real DOM node...
This will check for even if it is a jQuery or JavaScript DOM element
The following IE8 compatible, super-simple code works perfectly.
The accepted answer does not detect all types of HTML elements. For example, SVG elements are not supported. In contrast, this answer works for HTML well as SVG.
See it in action here: https://jsfiddle.net/eLuhbu6r/
old thread, but here's an updated possibility for ie8 and ff3.5 users:
For the ones using Angular:
https://docs.angularjs.org/api/ng/function/angular.isElement