get total width of children elements

Lewis picture Lewis · May 7, 2014 · Viewed 9.2k times · Source

I have some HTML tags:

<div id="container">
   <input type="text" id="a">
   <textarea id="b"></textarea>
   <div id="c" style="width:200px"></div>
   <div id="d" style="width:20%"></div>
</div> 

#a and #b have no css width attribute. How could I calculate the total width of container's children elements in pixel?

Answer

Andy picture Andy · May 7, 2014

Without jQuery, go this way:

var children = document.getElementById('container').children;
var totalWidth = 0;

for (var i = 0; i < children.length; i++) {
    totalWidth += children[i].offsetWidth;
}

To check whether you need offsetWidth or something else see
Stackoverflow - Understanding offsetWidth, clientWidth, scrollWidth and -Height, respectively