Search code examples
javascripthtmlgetelementbyidlit-element

Using two getElementByIds


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?


Solution

  • 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)