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?
This might be of interest:
It’s part of the DOM, Level2.
Update 2: This is how I implemented it in my own library: (the previous code didn’t work in Chrome, because Node and HTMLElement are functions instead of the expected object. This code is tested in FF3, IE7, Chrome 1 and Opera 9).