I am developing a function to find a particular element within another element identifier (similar to getElementById but that applies to any other element) … Because this throws me arror:
var ancestor = document.getElementById('divAncestor');
var child = ancestor.getElementById('divChild');
I know, HTML specifies that ids must be unique but reality proves that often running scripts that can have items with the same ids. So, thats the reason why I’m not simply calling the child like this:
var ancestor = document.getElementById('divChild');
The first option was to add this function to each HTML element, or at least the divs (because that’s what interests me identify). The second, and is the one I prefer, is to add a method to the dom document and call from there by passing the ID of the father and son as parameters.
Is this possible?
Thanks for your time.
Not discussing the bosh with non-unique ids, I will answer your actual question:
Yes, see How to extend the DOM with JS. But do not do it! The reasons are discussed very well in Kangax’ article What’s wrong with extending the DOM.
You could do this, yes, and would not cause too much harm. I’d guess it works well in all browsers, as you won’t have garbage-collection problems etc. anyway with a static function.
Yet I can’t see a good reason to do it. It sounds to me like abusing the
documentvariable as a namespace, while any other global variable or namespace object would’ve done it as well. For not creating possible (future) collisions, a dedicated namespace would be a better choice.