You could do it like this:
function getIndividualWidth(elementId,childrenCount){
var div = document.getElementById(elementId);
var totalWidth = div.offsetWidth;//500
//calculating childrenCount would require a function
//if you were not keeping track of it
return parseInt(totalWidth / childrenCount);
}
Here is one approach to counting the child elements of your div
function getChildElementCount(element){
var childCounter = 0;
var startPoint = element.childNodes;
for (var child in startPoint) {
if (startPoint[child].nodeType != 1) continue; //not an element
childCounter++;
}
return childCounter;
}
Which would change the function into this:
function getIndividualWidth(elementId){
var element = document.getElementById(elementId);
var totalWidth = element.offsetWidth;//500
return parseInt(totalWidth / getChildElementCount(element));
}
Deciding when to use this would depend on how your elements are rendered on the screen. If you had them already rendered, and just wanted to start from a certain parent, you could do this:
html (the spans are inline elements, so they would need display:inline-block
in order to actually reflect the change in width) see the jsfiddle here: http://jsfiddle.net/uhejM/
<div id="parent" style="width:500px;">
<span>1</span>
<span>2</span>
<span>3</span>
<span>4</span>
</div>
js
function getIndividualWidth(element){
return parseInt(element.offsetWidth / getChildElementCount(element));
}
function EqualizeChildWidths(element){
var width = getIndividualWidth(element);
var startPoint = element.childNodes;
for (var child in startPoint) {
if (startPoint[child].nodeType != 1) continue; //not an element
startPoint[child].style.width = width + "px";
}
}
EqualizeChildWidths(document.getElementById("parent"));