Thomas
Thomas

Reputation: 34198

How to insert space in table cell when generating table dynamically by javascript

i wrote a code to test one issue and notice that not being able to add space when generating table with data dynamically by javascript.

i use   to add some space but did not work.

full code here

<div id='table'>

</div>

var array = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];
var arrayLength = array.length;
var theTable = document.createElement('table');

// Note, don't forget the var keyword!
for (var i = 0, tr, td; i < arrayLength; i++) {
    tr = document.createElement('tr');
    td = document.createElement('td');
    td.appendChild(document.createTextNode('<span>'+array[i].id+'&nbsp;&nbsp;</span>'));
    tr.appendChild(td);

    td = document.createElement('td');
    td.appendChild(document.createTextNode('<span>'+array[i].foo+'&nbsp;&nbsp;</span>'));
    tr.appendChild(td);

    theTable.appendChild(tr);
}
//alert(theTable);
document.getElementById('table').appendChild(theTable);

looking for suggestion. thanks

Upvotes: 0

Views: 1269

Answers (3)

Wietse de Vries
Wietse de Vries

Reputation: 673

You could use CSS to add some padding.

#table td > span {
  padding-right:20px;
}

Upvotes: 0

Alex Barroso
Alex Barroso

Reputation: 859

You can continue the same way you did with td and tr. Create a new span element, then set the innerHTML. createTextNode is just for that, text, so the browser won't interpret tags and html entities.

var span = document.createElement('span');
span.innerHTML = array[i].id+'&nbsp;&nbsp;';
td.appendChild(span);

Upvotes: 1

Jan
Jan

Reputation: 43169

You can use the Unicode character for a space directly:

td.appendChild( document.createTextNode( '\u00A0' ) );

Can obviously be done a couple of times:

td.appendChild( document.createTextNode( '\u00A0\u00A0\u00A0' ) );
// three spaces

Upvotes: 0

Related Questions