Cannot read property of 'appendchild' of null in a For-Loop - javascript

I have a small database that I have retrieved the data from and stored in a HTML table.
This table contains 3 columns and 3 rows.
What I want to do is via javascript create a div for each row, then within this create a div for each cell in that row of the table (to allow me to style it in CSS).
I have created a number of For loops to go through and attempt this, my problem is the second for loop I have created, it goes through once and I receive an error of "Cannot read property 'appendChild' of null". I am not sure why it is doing this. Any help would be appreciated.
var getTable = document.getElementById('projectsTable');
var rowLength = getTable.rows.length;
for (i =0; i< rowLength; i++) {
var divName = 'projects' + i;
block = document.createElement('div');
block.id = divName;
document.getElementById('javascript').appendChild(block);
var getCells = getTable.rows.item(i).cells;
var cellLength = getCells.length;
for (var j = 0; j < cellLength; j++) {
var divName2 = 'projects' + j;
var projectInfo = 'info' + j;
info = document.createElement('div');
info.id = projectInfo;
document.getElementById(divName2).appendChild(info);
var cellVal = getCells.item(j).innerHTML;
var getDiv = document.getElementById(projectInfo);
getDiv.innerHTML = cellVal;
}
}
The first for loop creates the div for the whole row and attaches it to a div in the page that already exists, then I get the error on the 2nd for loop.

You are using many unnecessary variables and definitions. For example divName2 should be same as divName and thus redundant.
I hope this example helps you out.
<!DOCTYPE html>
<html>
<head>
<script>
function loadTable(){
var tT = document.getElementById('projectsTable'); //Source table
var tJ = document.getElementById('javascript'); //New clone container
if (tT && tJ){
for(var i=0, j=tT.rows.length;i<j;i++){
var tP = document.createElement('div'); //Our project div(:=tr)
tP.id = 'projects' + i.toString();
for(k=0, l=tT.rows.item(i).cells.length;k<l;k++){
var tI = document.createElement('div'); //Our info div(:=td)
tI.id = 'info' + k.toString();
tI.innerHTML = (i+1)*k;
tP.appendChild(tI); //We still have the correct project from above, so we just use it.
};
tJ.appendChild(tP); //Adding project to the dom
};
};
};
</script>
</head>
<body onload = 'loadTable();'>
<table id = 'projectsTable'>
<tr><td>1</td><td>2</td><td>3</td></tr>
<tr><td>4</td><td>5</td><td>6</td></tr>
</table>
<div id = 'javascript'></div>
</body>
</html>

Related

JavaScript createElement Line Causes Error

I'm writing a simple JavaScript program to examine every element in an HTML website and add a child node to every non-text node that labels the type of tag:
Here is my code:
window.onload = function() {
var body_elems = document.body.getElementsByTagName("*");
for (var i = 0; i < body_elems.length; i++) {
if (body_elems[i].nodeType != 3) {
var tag_name = body_elems[i].tagName;
var child = document.createElement("P");
var child_text = document.createTextNode(tag_name);
child.appendChild(child_text);
body_elems[i].appendChild(child);
body_elems[i].firstChild.className = "hoverNode";
}
}
}
For some reason the line var child = document.createElement("P") causes the page to never load; if I comment out that line then the page will load.
On the other hand, here is a slightly different version that actually works:
window.onload = function() {
var body_elems = document.body.getElementsByTagName("*");
for (var i = 0; i < body_elems.length; i++) {
if (body_elems[i].nodeType != 3) {
var tag_name = body_elems[i].tagName;
var child = document.createTextNode(tag_name);
body_elems[i].appendChild(child);
child.className="hoverNode";
}
}
}
But I can't figure out how to assign a class name to the new node in order to apply CSS, so if someone could tell me how to do that my problem would be solved.
I'm new to JS so any help would be much appreciated.

JavaScript : Delete dynamically created table

I am new to web development and struggling with deleting a dynamically created table.
Below is the JavaScript function to create the table when user clicks a button.
function DrawTable(data){
var oTHead = myTable.createTHead();
var oTFoot = myTable.createTFoot();
var oCaption = myTable.createCaption();
var oRow, oCell;
var i, j;
var heading = new Array();
heading[0] = "AAA";
heading[1] = "BBB";
heading[2] = "CCC";
heading[3] = "DDD";
var tableData = data.split(':');
// Insert a row into the header.
oRow = oTHead.insertRow(-1);
oTHead.setAttribute("bgColor","lightskyblue");
// Insert cells into the header row.
for (i=0; i < heading.length; i++)
{
oCell = oRow.insertCell(-1);
oCell.align = "center";
oCell.style.fontWeight = "bold";
oCell.innerHTML = heading[i];
}
// Insert rows and cells into bodies.
for (i=0; i < tableData.length; i++)
{
var oBody = oTBody0;
oRow = oBody.insertRow(-1);
var splitData = tableData[i].split(',');
for (j=0; j < splitData.length; j++)
{
oCell = oRow.insertCell(-1);
oCell.innerHTML = splitData[j];
}
}
}
The above code works perfectly and draws the table when user clicks on the button.
If user clicks on the button again it will draw the table again.
i.e., it will draw another header and all the rows all over again.
At this point I want to delete the existing header and rows and draw it all new.
I tried many things to delete the existing table, but nothing works.
Is there a way I can make sure that the table is not duplicated again?
UPDATE
The HTML part is:
<table id="myTable">
<tbody ID="oTBody0"></tbody>
</table>
ANOTHER UPDATE
I tried below and it worked.
oTHead.innerHTML = "";
oTBody0.innerHTML = "";
jQuery offers a .empty() function that you can use
$("#myTable").empty();
Or with javascript you can just set the innerHTML to empty
document.getElementById("myTable").innerHTML = "";
Just execute this function before you start trying to add new content to the table.
//$("#myTable").empty();
document.getElementById("myTable").innerHTML = "";
// Insert a row into the header.
oRow = oTHead.insertRow(-1);
oTHead.setAttribute("bgColor","lightskyblue");
// Insert cells into the header row.
for (i=0; i < heading.length; i++) {
oCell = oRow.insertCell(-1);
oCell.align = "center";
oCell.style.fontWeight = "bold";
oCell.innerHTML = heading[i];
}
Since you're using jQuery, just do this: $('#containerIdThatYourTableSitsIn').html('');
That will clear the html of whatever element your table sits in. Then just reload it.
Edit
As the comments have mentioned, .empty() is another option.

Why can't I get my images to appear in table cells/nodes.. maybe I can get some closure?

I want to add a new image in each cell of the new table and give it the same source as the old table, and then make it clickable. Firstly, I did this:
function showData() {
if (localStorage.getItem(name) !== null) {
var showme = localStorage.getItem(name);
alert("I got the table");
var newTable = document.createElement('table');
newTable.innerHTML = showme;
newTable.id = "newTable";
newNumRows = newTable.getElementsByTagName('tr').length;
newNumCells = newTable.getElementsByTagName('td').length;
newNumCols = newNumCells / newNumRows;
alert(newNumRows);
alert(newNumCells);
alert(newNumCols);
var newImages = newTable.getElementsByTagName('img');
for (var i = 0; i < newImages.length; i += 1) {
var picSource = newImages[i]['src'];
console.log(picSource);
}
function addNewImage(newNumCols) {
var newImg = new Image();
newImg.src = picSource;
col.appendChild(newImg);
newImg.onclick = function() {
alert("WOW");
};
}
for (r = 0; r < newNumRows; r++) {
row = newTable.insertRow(-1);
for (c = 0; c < newNumCols; c++) {
col = row.insertCell(-1);
addNewImage(newNumCols);
}
}
var showIt = document.getElementById('holdTable');
showIt.appendChild(newTable);
}
}
This works to a certain extent, but, unfortunately, only the last image was displaying. So, I did a bit of looking around and I think it has to do with closure (apologies for any duplication), but it's a concept I am really struggling to understand. So then I tried this:
function showData() {
if (localStorage.getItem(name) !== null) {
hideTaskForm();
var showme = localStorage.getItem(name);
var oldTable = document.createElement('table');
oldTable.innerHTML = showme;
newTable = document.createElement('table');
newTable.id = "newTable";
var i, r, c, j;
newNumRows = oldTable.getElementsByTagName('tr').length;
newNumCells = oldTable.getElementsByTagName('td').length;
newNumCols = newNumCells / newNumRows;
var newTableCells = newTable.getElementsByTagName('td');
var getImages = oldTable.getElementsByTagName('img');
for (r = 0; r < newNumRows; r++) {
row = newTable.insertRow(-1);
for (c = 0; c < newNumCols; c++) {
makeNodes = row.insertCell(-1);
}
}
for (var j = 0; j < newTableCells.length; j++) {
var theNodeImage = document.createElement("img");
newTableCells[j].appendChild(theNodeImage);
alert(newTableCells[j].innerHTML); //This gives me img tags
}
for (i = 0; i < getImages.length; i += 1) {
var oldSource = getImages[i]['src']; //gets the src of the images from the saved table
console.log(oldSource);
//alert(oldSource);//successfully alerts the image paths
var newPic = new Image(); //creates a new image
(function(newPic, oldSource) {
newPic.src = oldSource;
alert(newPic.src); //gives the same image paths
newTable.getElementsByTagName('img').src = newPic.src; //This doesn't work - table is blank???
})(newPic, oldSource);
}
var showIt = document.getElementById('holdTable');
showIt.appendChild(newTable);
}
}
Now, this doesn't throw any errors. However, nor does it fill the table. It does give me the source and I think I have created the new image objects to attach to the img tags in the newTableCells, but the table is showing up blank. I don't know where I am going wrong. All help really welcome.
Note: Even as a hobbyist, even I know there are probably tons of more efficient ways to do this, but I purposely did it this way to try and help me understand the logic of each step I was taking.
In your code you have:
var newImages = newTable.getElementsByTagName('img');
for (var i = 0; i < newImages.length; i += 1) {
var picSource = newImages[i]['src'];
console.log(picSource);
}
At the end of this, picSource has the value of the last image's src attribute. Then there is:
function addNewImage(newNumCols) {
var newImg = new Image();
newImg.src = picSource;
col.appendChild(newImg);
newImg.onclick = function() {
alert("WOW");
};
}
A value is passed to newNumCols but not used in the function. The value of picSource comes from the outer execution context and is not changed, so it's still the last image src from the previous for loop.
for (r = 0; r < newNumRows; r++) {
row = newTable.insertRow(-1);
for (c = 0; c < newNumCols; c++) {
col = row.insertCell(-1);
addNewImage(newNumCols);
}
}
This loop just keeps calling addNewImage with a single parameter that isn't used in the function, so you get the same image over and over.
For the record, the addNewImage function does have a closure to picSource, but it also has a closure to all the variables of the outer execution contexts. This isn't the issue, though it perhaps masks the fact that you aren't setting a value for picSource on each call, so you get the left over value from the previous section of code.
You haven't provided any indication of the content of showme, so it's impossible to determine if this approach will work at all.
Note
Where you have:
var showme = localStorage.getItem(name);
alert("I got the table");
var newTable = document.createElement('table');
newTable.innerHTML = showme;
newTable.id = "newTable";
IE does not support setting the innerHTML property of table elements, though you can create an entire table as the innerHTML of some other element and set the innerHTML of a cell (tr, th). If you want to use this approach, consider:
var div = document.createElement('div');
div.innerHTML = '<table id="newTable">' + showme + '<\/table>';
var newTable = div.firstChild;

Storing the index of a for loop in javascript

I'm developing an android app with phonegap. I'm making an HTML table with some that with a for loop from localStorage. I need, for each row, to store the index i of the for to use it for retrieving an item from localStorage that has the name like the index. I have some code but the variable that i defined for that effect gets overwritten by the loop (of course). Here's the code:
<script language="javascript">
if(len != 0) {
var table = document.getElementById('hor-minimalist-b'); // get the table element
var tableBody = table.childNodes[1]; // get the table body
var tableHead = table.childNodes[0]; // get the table head
var thead = document.createElement('th');
var row2 = document.createElement('tr'); // create a new row
var headText = document.createTextNode('Dados');
thead.scope = "col";
thead.appendChild(headText);
row2.appendChild(thead);
tableHead.appendChild(row2);
for (var i=0; i<len; i++) {
var row = document.createElement('tr'); // create a new row
var cell = document.createElement('td'); // create a new cell
var a = document.createElement('a');
var cellText = document.createTextNode(localStorage.getItem('key' + i));
var xyz = "key" + i;
a.href = "alterar.html";
a.onclick = function() { doLocalStorage(xyz) };
a.appendChild(cellText);
cell.appendChild(a); // append input to the new cell
row.appendChild(cell); // append the new cell to the new row
tableBody.appendChild(row); // append the row to table body
}}
</script>
</table>
Maybe i'm not explaining myself too well. If you need any more info please ask. Thanks in advance. Eva
try to put the key name in to a closure:
function wrapper(i) {
return function() {
doLocalStorage("key" + i)
}}
a.onclick = wrapper(i);
Not sure if I got your question right, but if you want to bind usage of a variable asynchronously when doing for loop then you should wrap it in a closure:
for(i = 1, c = arr.length; i < c; i++){
(function(i){
// i wont change inside this closure so bound events will retain i
$('#id'+i).click(function(){
alert(i); // Will alert the corresponding i
})
})(i);
}

How do I access DOM nodes from an array in javascript?

I am trying to build a drop-down menu that will show a row to the side of it when you hover over one of the cells with the mouse. I'm really new with using the DOM, and javascript as well.
The problem I'm running into is that the array I have created doesn't seem to access what I thought it should. Is it just my syntax, or do I need to approach this differently? Here is my code:
window.onload = function () {
var tableID = "strokerKitMenu";
var table = document.getElementById(tableID);
var tableRows = table.getElementsByTagName("tr");
var tableCell = [];
var counter = 0;
for (i = 0; i < tableRows.length; i++) {
tableCell[i] = new Array();
tableCell[i].push(tableRows[i].getElementsByTagName("td"));
}
for (i = 0; i < tableCell.length; i++) {
tableCell[0, i].style.display = "block"; //This doesn't compile
alert(tableCell[0, i].Text); //This comes back "undefined"
for (j = 1; j < tableCell[i].length; j++) //I haven't even tested this part yet
{
tableCell[i][j].onmouseover = function showCell() {
tableCell[i][j + 1].style.display = "block";
}
tableCell[i][j].onmouseout = function hideCell() {
this.style.display = "none";
}
} //end inner for loop
} //end outer for loop
}
tableCell[0, i].style.display="block"; //This doesn't compile
This syntax is invalid in JavaScript: you have specified two indices for tableCell but I guess you meant tableCell[0][i].style.display="block";
alert(tableCell[0, i].Text); //This comes back "undefined"
Once you fix the first error, you will want to change this to tableCell[0][i].textContent.
tableCell[i].push.apply(tableCell[i], tableRows[i].getElementsByTagName("td"));
You don't want to push the single array in. You want to push all the elements in. Otherwise you would have to access them as tableCell[i][0][j]

Categories

Resources