Sometimes, we want to select an item with a class within a div with JavaScript.
In this article, we’ll look at how to select an item with a class within a div with JavaScript.
Use document.querySelector
We can use document.querySelector
on to select a div and then select an element within it with the given class after that.
For instance, if we have the following HTML:
<div id="mydiv">
<div class="myclass"></div>
</div>
Then we can select the div with the class myclass
by writing:
const innerDiv = document
.querySelector('#mydiv')
.querySelector('.myclass')
console.log(innerDiv)
We just call querySelector
on the element with the ID mydiv
to select items inside that div.
Therefore, innerDiv
is the div with the class myclass
.
Use document.getElementById
We can replace the first querySelector
call with getElementById
.
For instance, if we have the following HTML:
<div id="mydiv">
<div class="myclass"></div>
</div>
Then we can select the div with the class myclass
by writing:
const innerDiv = document
.getElementById('mydiv')
.querySelector('.myclass')
console.log(innerDiv)
Then we see the same result as before.
Use document.getElementsByClassName
Also, we can use the getElementsByClassName
method to get all the elements with the given class within an element.
For instance, if we have the following HTML:
<div id="mydiv">
<div class="myclass"></div>
</div>
Then we can select the div with the class myclass
by writing:
const [innerDiv] = document
.getElementById('mydiv')
.getElementsByClassName('myclass')
console.log(innerDiv)
We restructure the first div with the class myclass
from the elements that are returned by getElementsByClassName
.
And we get the same result as before.
Conclusion
We can get elements within an element with the element selection methods built into the browser.