Reputation: 7192
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.
Upvotes: 0
Views: 121
Reputation: 665020
Not discussing the bosh with non-unique ids, I will answer your actual question:
Is it possible to add a method to the DOM document?
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.
The second method, was to add a method to the dom document and call from there by passing the ID of the father and son as parameters.
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 document
variable 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.
Upvotes: 1
Reputation: 72937
Use this:
document.querySelector("div#divAncestor div#divChild");
This gets the first div
with id="divChild"
in the div
with id="divAncestor"
While ID's Must be unique, as per the specification, it is indeed possible that they aren't.
(Browsers deal with it just fine)
While your priority "should be" to prevent this, the code above works.
In case there are multiple ancestors or children, this should work:
document.querySelectorAll("div#divAncestor div#divChild");
These querySelectors work like css selectors. Select classes like: div.className
, multiple elements like this: div, p, h1
, etc.
Upvotes: 2