Suppose I have these three spaces that are blank to start with. I want to change using innerHTML in JavaScript.
<p id="topname"></p>
<div id="table"></div>
<p id="botname"></p>
document.getElementById("topname").innerHTML = "Boy";
document.getElementById("botname").innerHTML = "Girl";
I managed to change topname and botname with the innerHTML. How do I change div id="table" to display an x by y (2x2, 4x4, 8x8,etc.) table?
Instead of replacing the <div> with a <table>, it is recommended to create a <table> as a child node of the <div> As long as you have not added additional styling to the <div> (like padding or margins), this will have no effect on the display.
A couple of loops to build <tr> and <td> will do the job. Here's a function that takes x and y:
function makeTable(rows, cols) {
// Create a table node
var tbl = document.createElement('table');
// Make a <tr> for each row
for (var i=0; i<rows; i++) {
var tr = document.createElement('tr');
// And make a <td> for eah col
for (var j=0; j<cols; j++) {
var td = document.createElement('td');
// Append them to the current tr
tr.appendChild(td);
}
// Append the row
tbl.appendChild(tr);
}
return tbl;
}
// Create a new 2x4 table with the function
var newTable = makeTable(2, 4);
// And append it as a child to the <div id='table'>
document.getElementById('table').appendChild(newTable);
Here it is in action
You should be able to do it the same way, however, that div id might be giving you issues. TABLE is an html entity unto itself. I would rename that.
document.getElementById("table").innerHTML = "<table><caption>Caption</caption><thead>Table Header</thead><tfoot>Table Footer</tfoot><tbody><tr><td>1</td><td>2</td></tr><tr><td>3</td><td>4</td></tr></tbody></table>";
And what Shadow Wizard said above. It is best to use the right tool for the job. My answer is solely if you insist on doing it within a div.
First of all, change your div to a table manually:
<table id="table"></table>
With following code you can fill your table with rows and columns:
document.getElementById("table").appendChild(makeTable(2, 4));
function makeTable(rows, cols) {
var table = document.createDocumentFragment(), tr = document.createElement("tr"), td = document.createElement("td"), i, j;
for(j = 0; j < cols; j++) tr.appenChild(td.cloneNode(true));
for(i = 0; i < rows; i++) table.appendChild(tr.cloneNode(true));
return table;
}
Related
I want to dynamically create 10 tables and append it in div container with class table_container.
This is the snippet I was trying, do i need to make any changes in it for my requirement?
for( let i =0; i< 10; i++){
var table = document.createElement('table');
table.setAttribute("id", "table"+i);
}
<div class="table_container">
</div>
// Get a reference to the container.
const container = document.querySelectorAll('.table_container')[0];
for(let i = 0; i < 10; i++){
// Create the new <table>
const table = document.createElement('table');
table.setAttribute("id", "table"+i);
// Append it to the inside of the container.
container.appendChild(table);
}
When I update an HTML table using appendChild(), the entire table is moved to the bottom of the document. How do I preserve the location of the table in the DOM?
My example is also posted on JSFiddle.
<!--I want the existing table below to stay fixed in place after new rows are added.-->
<table id="table">
<tr>
<td> Table Cell 1</td>
<td> Table Cell 2</td>
</tr>
</table>
<!--The following button will add rows, but also move the table. How do I stop the move?-->
<input type="button" value="ADD NEW ROWS." onclick="generate_table()">
<script>
// This function just creates new rows for the table
function generate_table() {
var body = document.getElementsByTagName("body")[0];
var tbl = document.getElementById("table");
var tblBody = document.createElement("tbody");
for (var i = 0; i < 2; i++) {
var row = document.createElement("tr");
for (var j = 0; j < 2; j++) {
var cell = document.createElement("td");
var cellText = document.createTextNode("cell " + i + ", column " + j);
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
}
</script>
<style>
table,
th,
td {
border: 1px solid black;
border-collapse: collapse;
}
</style>
Remove the following line, you don't need it.
body.appendChild(tbl);
The table node is already a part of the Document Object Model, you don't need to add it again. By appending the element to body, you are moving it from the current position to the end of the body node.
As a rule of thumb, you need to use appendChild, only if the element was created dynamically using createElement.
Below is the JavaScript functionalities addRow() I have used to add the rows dynamically and now am trying to highlight the selected row with red color using rowhighlight() function.
/Function to addRows dynamically to the HTML table/
function addRow(msg)
{
var table = document.getElementById("NotesFinancialSummary");
var finSumArr1 = msg.split("^");
var length = finSumArr1.length-1;
alert("length"+ length);
for(var i=1; i<finSumArr1.length; i++)
{
var rowValues1 = finSumArr1[i].split("|");
tb=document.createElement("tbody");
var tbody=document.createElement("tbody");
table.appendChild(tbody);
var tr=document.createElement("tr");
tbody.appendChild(tr);
for(var k=0;k<=10;k++)//adding data to table dynamically
{
var td=document.createElement("td");
tr.appendChild(td);
var element1=rowValues1[k];
td.innerHTML =element1;
tr.onclick=function(){
rowhighlight(this);//calling the rowhighlight function
}
}
}
}
function rowhighlight(x)
{
var index = x.rowIndex;
document.getElementById("NotesFinancialSummary").rows [index].style.backgroundColor = "red";
}
One approach is to first loop through the other rows and remove the styling (really should be a class) then apply the styling (again, class) to the selected row.
Here's one way of doing it:
function rowHighlight() {
var selectedRows = document.getElementsByClassName('selected');
for (var n = 0; n < selectedRows.length; n++) {
selectedRows[n].className = '';
}
this.className = 'selected'
}
And here's a working example of it, though very simple: fiddle time!
I have the following function to append rows and cells to an empty table:
function createTable(size) {
var table = document.getElementById("gameTable");
for (var i=0; i<size; i++) {
var tr = document.createElement("tr");
for (var j=0; j<size; j++) {
var td = document.createElement("td");
tr.appendChild(td);
}
table.appendChild(tr);
tr.rowIndex = i;
}
}
So far so good.
My problem is that later, when I tried to reach specific cells inside the table:
var x = target.parentNode.rowIndex;
var y = target.cellIndex;
table.rows[x].cells[y].innerHTML = 'blah'
target is the specific TD that was clicked.
the rows[x] index is always -1. Every time I try the line above I get an error: "cannot read property 'cells' of undefined"
I even tried manually setting the rowIndex of each Row to what it should be (inside the function), but to no avail.
The cellIndex comes out fine, but the rowIndex is -1 and each and every one of the newly created table rows.
What can I do to correct this?
This can be solved by appending the <tr> elements into a <tbody>.
function createTable(size) {
var table = document.getElementById("gameTable");
var tb = document.createElement("tbody");
for (var i=0; i<size; i++) {
var tr = document.createElement("tr");
for (var j=0; j<size; j++) {
var td = document.createElement("td");
tr.appendChild(td);
}
tb.appendChild(tr);
}
table.appendChild(tb);
}
I want to loop through rows on a table and only execute a change background color if column2 cells contain no values or empty cells. This is what I have now but all my rows are colored and I only need the logic applied when cells in column2 are empty.
JS:
// loops through rows
for (var i = 0; rows; rows = tbody.rows[i]; i++) {
//loops through cells
for (var j = 1; col; col = rows.cells[j]; j++) {
//gets cells of current row
cells = rows[i].getElementsByTagName('td');
//gets cells of col 1
ocells = rows.cells[j].getElementByTagName('td');
while (rows.cells[j] === null) {
//condition here>>
}
}
}
HTML:
<div id="table">
<table name="tbody" id="tbody1">
<tr>
<td>col1 Val1</td>
<td>col2 Val2</td>
</tr>
<tr>
<td>col1 Val3</td>
<td>col2 Val4</td>
</tr>
</table>
</div>
Any help would be appreciated!
I would rethink the necessity to loop over everything to do this:
If you made the table (or it is generated), add a class to each cell in column 2.
Let's call this class: "column-2-cell"
Now using jQuery:
$('.column-2-cell:empty').addClass('empty');
See this fiddle: http://jsfiddle.net/Ubz6w/
Optionally you can also use this with jQuery:
$('tr').each(function(i) {
var column2cell = $($(this).children('td')[1]);
if (column2cell.text() == "") {
column2cell.css('background-color', 'red');
}
});
See this fiddle: http://jsfiddle.net/Ubz6w/1
Hope this helps!
Just use this. This will set the background of the second column if it is empty.
var tbody = document.getElementsByName("tbody")[0];
for (var i = 0, rows; rows = tbody.rows[i]; i++) {
if(rows.cells[1].innerHTML == "") {
rows.cells[1].className += "highlight";
}
}
Live Demo