var row = document.createElement("tr");
let ex = document.createElement("td");
ex.className = "clickable";
ex.id = "exampleid";
/ * Outputs normally here * /
row.appendChild(ex);
table.appendChild(row);
console.log(table.rows[0].id);
/ * Outputs "" instead of "exampleid" * /
When trying to access an element from a table, the ID I assigned becomes a blank string. How can I retain the assigned ID? For context, I was using for loops to produce an array of elements.
Tried console.log(table.rows[0].id)
, got ""
CodePudding user response:
The id assigned is on the td
element not the tr
element.
You need to access the child of tr only then the id will be available.
To access you can either use .children
-> gives a list.
or since this is a table, you can use .cells
var table = document.createElement("table");
var row = document.createElement("tr");
let ex = document.createElement("td");
ex.className = "clickable";
ex.id = "exampleid";
row.appendChild(ex);
table.appendChild(row);
console.log(table.rows[0].id); // this is the id for first row
console.log(table.rows[0].children[0].id); // this is the id for td element inside tr
console.log(table.rows[0].cells[0].id);