Is it possible to do something like:
this.getElementById('first-id').getElementById('second-id')?
When I do this, I get an error "getElementById(...).getElementById is not a function.
The reason I'm trying to do this is because I am able to console log the first-id element, but not the second (when I do this.getElementById('second-id')). I assume it is because my DOM is not completely loaded.
However, I thought since it loaded the first-id element, I'll be able to do another getElementById as the first part is loaded and the next element is nested/a child of the first-id element.
Can someone explain why this logic doesn't work?
An element with a given ID is supposed to be absolutely unique in a document. There should never be more than one element with the same ID. So, calling getElementById on an element to search among its children, if it were possible (which it isn't), wouldn't make a whole lot of sense - instead, search from the whole document. You should only need
document.getElementById('second-id')
Most answers here are correct and will help the OP implement the solution. This will try to answer Is it possible to do something like:, which is what OP asked originally:
this.getElementById('first-id').getElementById('second-id')
getElementById() is a Document interface method and is only available on the Document object. It is not available on the Element, and this.getElementById('first-id').getElementById will be equal to undefined. undefined is not a function and can't be invoked, hence the error.
It makes sense that getElementById() is only available in the Document interface as an ID is (ideally) supposed to be a unique in the DOM. So, providing the function inside other elements is not as useful.
querySelecetor() is both a document and element method and is available on both the objects.
That is why you can do something like :
document.querySelector('#first-id').querySelector('#second-id')
(Searches for #second-id child of #first-id)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With