Skip to content

Instantly share code, notes, and snippets.

@shaunwallace
Last active December 31, 2015 18:09
Show Gist options
  • Save shaunwallace/8025178 to your computer and use it in GitHub Desktop.
Save shaunwallace/8025178 to your computer and use it in GitHub Desktop.
Computing the total width of all children elements inside of a given parent
//with jQuery
var parent = $(selector)
, totalWidthOfChildren = Array.prototype.reduce.call(parent.children(), function(a,b){ return a + $(b).outerWidth( true ); }, 0);
//without jquery
var parent = document.getElementById('selector')
, totalWidthOfChildren = Array.prototype.reduce.call(parent.children, function(a,b){ return a + outerWidth(b); }, 0);
function outerWidth( elem ) {
var styles;
if( window.getComputedStyle ) {
var parts = ["width", "paddingLeft", "paddingRight", "marginLeft", "marginRight"];
styles = window.getComputedStyle( elem );
return parts.reduce(function(a,b) {
return a + +styles[b].replace(/px/, '');
}, 0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment