3

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?

Lewis
  • 14,132
  • 12
  • 66
  • 87

4 Answers4

18

Without jQuery, go this way:

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

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

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

Tim
  • 6,281
  • 3
  • 39
  • 49
Andy
  • 3,997
  • 2
  • 19
  • 39
2

This code is shorter and use vanilla-js:

const el = document.querySelector('.some-el')
const totalWidth = Object.values(el.childNodes).reduce((total, i) => total + i.offsetWidth, 0)
console.log(totalWidth)
  • 1
    Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Mark Rotteveel Oct 21 '20 at 10:11
0

With jQuery, you can do it like this:

var width = 0;

$('#container').children().each(function () {
    width += $(this).outerWidth(); 
    // change to .outerWidth(true) if you want to calculate margin too.
});


console.log(width);
display-name-is-missing
  • 4,424
  • 5
  • 28
  • 41
  • 1
    I've tried your method. However, it didn't calculate the default width of `#a` and `#b`. – Lewis May 07 '14 at 15:12
0

var totalWidth = 0;
document.querySelectorAll('#container > *').forEach(function(child) {
  totalWidth += parseInt(child.offsetWidth, 10);
});

console.log('Total Width: ', totalWidth);
<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>
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 10 '22 at 08:52