Sometimes, we want to get max width of child divs with JavaScript.
In this article, we’ll look at how to get max width of child divs with JavaScript.
How to get max width of child divs with JavaScript?
To get max width of child divs with JavaScript, we can select all the divs, spread them into an array, and then get their widths using the clientWidth
property with the array map
method.
Then we use Math.max
to get the max width.
For instance, we write:
<div id="wrapper">
<div class="image"><img src="https://picsum.photos/180/300
"></div>
<div class="image"><img src="https://picsum.photos/220/300
"></div>
<div class="image"><img src="https://picsum.photos/230/300
"></div>
<div class="image"><img src="https://picsum.photos/100/100
"></div>
<div class="image"><img src="https://picsum.photos/150/300
"></div>
<div class="image"><img src="https://picsum.photos/250/300
"></div>
</div>
to add divs with images.
Then we write:
window.onload = () => {
const widths = [...document.querySelectorAll('.image')].map(i => i.clientWidth)
const maxWidth = Math.max(...widths)
console.log(maxWidth)
}
to get the divs with class image
with querySelectorAll
.
Then we spread them into an array and use map
with a callback to return their clientWidth
, which is the width of each div.
Next, we call Math.max
with the widths
array spread into it as arguments.
Therefore, we see that maxWidth
is 253.
Conclusion
To get max width of child divs with JavaScript, we can select all the divs, spread them into an array, and then get their widths using the clientWidth
property with the array map
method.
Then we use Math.max
to get the max width.