Consider the following approach:
// Define variables within the local scope:
var names=["heihachi", "forest law"],
values=[22, 31],
// Get a reference to the element outside of the loop (once, not multiple times):
test = document.getElementById('test'),
// Create a new span element for wrapping text:
span = document.createElement('span'),
// Declare a variable for working with the node:
_temp;
// Ensure 'position: relative' to move elements/words around:
span.style.position = 'relative';
// Iterate over the names array:
for (var i = 0, len = names.length; i < len; i++)
{
// Work on a clone of the 'span':
_temp = span.cloneNode();
// Append a child textNode to the cloned node:
_temp.appendChild(document.createTextNode(names[i]));
// Set the left property of the node's style object:
_temp.style.left = values[i] + 'px';
// Append the node to the 'test' node:
test.appendChild(_temp);
}
JS Fiddle demo.
Alternatively, you can create an array of objects, each containing a name
and value
property:
var namesAndPositions = [{
'name' : 'heihachi',
'value' : 22
},{
'name' : 'forest law',
'value' : 31
}],
test = document.getElementById('test'),
span = document.createElement('span'),
_temp;
span.style.position = 'relative';
for (var i = 0, len = namesAndPositions.length; i < len; i++)
{
_temp = span.cloneNode();
_temp.appendChild(document.createTextNode(namesAndPositions[i].name));
_temp.style.left = namesAndPositions[i].value + 'px';
test.appendChild(_temp);
}
JS Fiddle demo.
To achieve the measurement (22px
and 31px
to the left of each element), use display: inline-block
and set marginLeft
:
// Code above remains unchanged
span.style.display = 'inline-block';
for (var i = 0, len = namesAndPositions.length; i < len; i++)
{
_temp = span.cloneNode();
_temp.appendChild(document.createTextNode(namesAndPositions[i].name));
_temp.style.marginLeft = namesAndPositions[i].value + 'px';
test.appendChild(_temp);
}
JS Fiddle demo.
References: