How do I make a div appear in the center of a dynamically created table row?

Advertisements

I want to create a div inside a table row, and the catch is that it should be in the center of that row. This is my code:

table.rows[0].cells.item(0).innerHTML = "<b>Confirm all</b>";
var inp = document.createElement("INPUT");
inp.setAttribute("type","checkbox");
table.rows[0].cells.item(1).appendChild(inp);
var row = table.insertRow(1);
row.style.padding="5px";
var span = document.createElement("div");
span.style.width="100%";
span.style.textAlign="center";
span.style.verticalAlign="center";
span.style.lineHeight="50px";
span.innerText = "OR";
row.appendChild(span);

This is the output that I get:

enter image description here

As you can see in the image, the div is always there in the left side of the row, I want it to be in the center. How do I do that?

>Solution :

Your code almost works. To make the text in the center of your table row, you just put your span/div element inside td element. Try to replace this:

row.appendChild(span);

with this

var td = document.createElement("td");
td.colSpan = "2";
td.appendChild(span);
row.appendChild(td);

Don’t forget to add colspan attribute in the td element. Full code:

document.getElementById("rep_tab").rows[3].cells.item(0).innerHTML = "<b>Confirm all</b>";
var inp = document.createElement("INPUT");
inp.setAttribute("type","checkbox");
document.getElementById("rep_tab").rows[3].cells.item(1).appendChild(inp);
var row = document.getElementById("rep_tab").insertRow(4);
row.style.padding="5px";
var span = document.createElement("div");
span.style.width="100%";
span.style.textAlign="center";
span.style.verticalAlign="center";
span.style.lineHeight="50px";
span.innerText = "OR";

// new code
var td = document.createElement("td");
td.colSpan = "2";
td.appendChild(span);
row.appendChild(td);
<table id="rep_tab" border="1">
  <tr>
    <td>cell 1</td>
    <td>cell 2</td>
  </tr>
  <tr>
    <td>cell 3</td>
    <td>cell 4</td>
  </tr>
  <tr>
    <td>cell 5</td>
    <td>cell 6</td>
  </tr>
  <tr>
    <td>cell 7</td>
    <td>cell 8</td>
  </tr>
</table>

Leave a Reply Cancel reply