How to get child of a parent elements and it’s total width in Javascripts ?
You can get multiple child of a parent element by using JavaScript Array forEach() or you can use for loops. Also we can sum of all the children elements width. Here is the example:
//html structure
<div class="parent">
<div class="child">Child 1</div>
<div class="child">Child 2</div>
<div class="child">Child 3</div>
</div>
<div class="parent">
<div class="child">Child 1</div>
<div class="child">Child 2</div>
<div class="child">Child 3</div>
</div>
//JavaScript code
<script>
const parentClass = document.querySelectorAll(".parent");
const childClass = document.querySelectorAll(".child");
parentClass.forEach(item => {
x = item.children;
//Sum of children width value
let sum = 0;
for (let i = 0; i < x.length; i++) {
sum += x[i].offsetWidth;
getChildren = x[i];
}
// find all the children elements
console.log(getChildren);
// Find all child elements total
console.log('Total width of child elements :' + sum);
}
</script>