I recently faced a problem with determining browsers’ support for certain DOM features. One of them was Element.children feature, which is still causing me headache. I have the following line in my code:
var NATIVE_CHILDREN = Element.prototype.hasOwnProperty(‘children’);
It is supposed to check if the browser supports Element.children -feature [https://developer.mozilla.org/en/DOM/Element.children].
According to MDN and quick testing, all the major browsers support this feature.
On Firebug on Firefox, value of NATIVE_CHILDREN is expectedly true. Surprisingly, on Chrome, Safari and Opera the value is false (unfortunately I don’t have accees to machine with Windows to check what IE thinks about it).
According to DOM4 – Free Editor’s Draft 5 April 2012 [http://dom.spec.whatwg.org/#element], children should be part of Element object’s prototype. Apperantly Chrome’s, Safari’s and Opera’s Element object doesn’t contain such a method!
I have tried checking the prototypes of HTMLCollection and Node (I also tested HTMLParagraphElement and HTMLBodyElement), but none of them seem to contain method called ‘children’ (except on Firefox). How can I make my test to work cross-browser? I don’t want to use any external libraries for this, because this is for my own little library.
I think the reason why this test might return false on Chrome is that you’re checking on the prototype. This is not the best way, for several reasons:
Different browsers can (and do) use different implementations of the prototype, some prototypes are not accessible in IE for instance. In this case, I’d say your issue is the result of chrome relying on the (non standard)
__proto__property rather thenprototype. I can’t remember when, but I had a similar issue with chrome, and this was the source if the problem.AFAIK all browsers have a children property for their elements, though they behave differently in some cases, so I have some doubt as to the use of checking the existence of such a property.
If you still want to check this, why not use
document.body.hasOwnProperty('children')? Returns true on FF, Chrome, Safari and IE.