Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Element ID gets erased after being appended to a table

  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 ""

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);      
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading