You appear to have a couple issues.
divBox.getElementById("divID");
doesn't work because getElementById()
is only a method on the document
object. It is not a method on other types of objects. So, the divBox
element does not have that method. You could use document.getElementById("divID")
instead if there was only one divID
in the entire document and if divBox
was already inserted into the document.
var divContents = divBox.getElementsByClassName("divClass")[0];
works because .getElementsByClassName()
is a method on all DOM objects so it works when you call it on divBox
.
You call getElementById()
like this document.getElementById("someID")
.
If you want to find something in a particular part of the subtree, you can use element.querySelectorAll("#someID")
or if you want to have more than one object with a given identifier, then you can use a class name and use functions that find objects with a given class name.
As to your specific questions:
divBox.getElementById is not a function
That is because geetElementById()
is only a method on the document
object and divBox
is not a document
object so it does not have that method, therefore you get the error you are seeing.
Why does this have no issue:?
var divContents = divBox.getElementsByClassName("divClass")[0];
That is apparently because divClass
is a class name, not an id value and all HTML elements contain the getElementsByClassName()
method so you can call it on divBox
just fine.