Give the specific container an additional, generated class name and add a style
element (here's how) with the relevant rule, e.g.:
.array-container.width-28 > span { width : 28px }
...if the width you want is 28px.
You'd change this line:
container.setAttribute('class','array-container');
to
container.className = 'array-container width-' + width;
Keep track of the style
elements you add so that if you need a value twice, you don't have to add a second style
element for the same value.
Here's a really quick and dirty example: Live Copy
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Dynamic Style Example</title>
<style>
.array-container span {
display: inline-block;
border: 1px solid #08f;
height: 1em;
}
</style>
</head>
<body>
<label>Add elements with width:
<input type="number" value="10" min="10" max="10000" id="width-to-use">
</label>
<input type="button" value="Add" id="btn-add">
<script>
(function() {
document.getElementById("btn-add").onclick = function() {
var width, div, css, style;
width = parseInt(document.getElementById("width-to-use").value, 10);
if (isNaN(width)) {
return;
}
div = document.createElement('div');
div.innerHTML =
"<span></span>" +
"<span></span>" +
"<span></span>";
div.className = "array-container width-" + width;
if (document.getElementById("style-width-" + width) === null) {
css = ".array-container.width-" + width + " span { " +
"width: " + width + "px; " +
"}";
style = document.createElement('style');
style.id = "style-width-" + width;
style.type = "text/css";
if (style.styleSheet){
style.styleSheet.cssText = css;
}
else {
style.appendChild(document.createTextNode(css));
}
document.getElementsByTagName("head")[0].appendChild(style);
}
document.body.appendChild(div);
};
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
})();
</script>
</body>
</html>