Sometimes, we want to get element inside element by class and ID with JavaScript.
In this article, we’ll look at how to get element inside element by class and ID with JavaScript.
How to get element inside element by class and ID with JavaScript?
To get element inside element by class and ID with JavaScript, we can get the parent element.
And then we call the method to select the child element in the parent.
For instance, we write
const targetDiv = document
.getElementById("foo")
.getElementsByClassName("bar")[0];
to call getElementById
to get the parent element with ID foo
.
Then we call getElementsByClassName
with 'bar'
to select the elements with class bar
in the element with ID foo
.
Conclusion
To get element inside element by class and ID with JavaScript, we can get the parent element.
And then we call the method to select the child element in the parent.