Calculate Javascript pixel widths for list of elements

It seems like you mix up html and javascript syntax. Html are those <tag> things.

First of all, I recommend you this course or some other, just to get started with JavaScript.

To create an element in JS, you can either use document.write, which is probably much easier but may be used only before the document loads. You can use it like this:

width = 42; //or whatever
document.write('<div style="width: '+width+'px">adsf</div>');

Or the more difficult, but also more flexible way – to use the DOM. You would do it this way:

var div = document.createElement('div'); //create new element
div.style.width = 42; //set its width to whatever you want
div.textContent = "some text"; //add some text into the div
someElement.appendChild(div); //insert the element into another one

The someElement here is either an element you get by calling document.getElementById (or a similar function) or, if you want them directly inside the body, just write document.body.

.

With respect to @Marc_B’s answer, the final code would look something like this:

var list = [1,2,3,4];
var div;
for (var n = 0; n < array.length; n++) {
  div = document.createElement('div');
  div.style.width = 25*n;
  document.body.appendChild(div);
}

Leave a Comment