Using two getElementByIds
Solution 1:
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')
Solution 2:
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.
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
)
Solution 3:
You could possibly chain it using Document.querySelector()
, but you should never need to use this as ids should be unique.
E.g, something like this:
var selected = document.querySelector('#first-id #second-id');
console.log(selected);
<div id="first-id">
<div id="second-id">1</div>
</div>
<div id="second-id">2</div>
<!-- Don't use duplicate ids - this is just for demonstration -->