I have this JavaScript function to create a table with image cells:
function Draw(array) {
// get the reference for the body
var body = document.getElementsByTagName("body")[0];
document.clear();
// creates a <table> element and a <tbody> element
var tbl = document.createElement("table");
tbl.setAttribute("borderstyle", "1");
var tblBody = document.createElement("tbody");
// creating all cells
for (var j = 0; j < 4; j++) {
// creates a table row
var row = document.createElement("tr");
for (var i = 0; i < 4; i++) {
// Create a <td> element and a text node, make the text
// node the contents of the <td>, and put the <td> at
// the end of the table row
var cell = document.createElement("td");
var cellText = document.createElement(array[4 * j + i]);
cell.appendChild(cellText);
row.appendChild(cell);
}
// add the row to the end of the table body
tblBody.appendChild(row);
}
// put the <tbody> in the <table>
tbl.appendChild(tblBody);
// appends <table> into <body>
body.appendChild(tbl);
// sets the border attribute of tbl to 2;
tbl.setAttribute("border", "2");
}
but in
var cellText = document.createElement(array[4 * j + i]);
cell.appendChild(cellText);
row.appendChild(cell);
the cell.appendChild(cellText); doesn’t work!
I don’t know why and I don’t know how to resolve it!
update
the a array is this:
var a = Array(16);
for (var i = 0; i < 16; i++) {
a[i] = '<img src="' + i + '.jpg" />';
}
Updated answer
Re your comment:
It would have been useful if you’d told us that
array[4 * j + i]contained markup (included an example of it in the question, for instance).If the array contains markup, you don’t want to create a new node of any kind. Instead, assign to
innerHTMLof the table cell:When you assign to
innerHTML, the browser parses the markup and adds the relevant content to the element.Original answer before the comment below and before
array‘s content was given:To create a text node, you use
createTextNode, notcreateElement. So:Suppose
array[4 * j + i]was"Hi there". Yourdocument.createElement(array[4 * j + i])call was asking the DOM to create an element with the tag nameHi there, exactly the way thatdocument.createElement('div')asks it to create an element with the tag namediv.