Home > Software design >  Why is getElementsByClassName not working for dynamically created HTML elements?
Why is getElementsByClassName not working for dynamically created HTML elements?

Time:08-12

I am creating multiple dynamic HTML tables, and assigning a class to them. Like this:

 var x = document.createElement("TABLE");
 x.className = "table_pos_parts";
 //var row = x.insertRow(0);
 //var cell = row.insertCell(0);
 //var cell1 = row.insertCell(1);
 //cell.innerText = "abc";
 //cell1.innerText = 123;

 var x = document.createElement("TABLE");
 x.className = "table_pos_parts";
 //var row = x.insertRow(0);
 //var cell = row.insertCell(0);
 //var cell1 = row.insertCell(1);
 //cell.innerText = "def";
 //cell1.innerText = 456;

Now, when I console.log(x), I can see all the tables in my console, but when I start searching them by their classname:

console.log(document.getElementsByClassName("table_pos_parts")); //shows empty
console.log(document.getElementsByClassName("table_pos_parts").length); //prints 0

it shows empty. Why?

CodePudding user response:

Fix:

You didn’t add the x to the document.body, to fix this, use document.body.append(x) and then in the console you will get it.

Improvement: Also, your var x used two times, which means the x will record the last element that is appended, if later on you want to change it, then can’t. To fix it, just change the second element’s variable name to other name (but must not be called “x”) and also the names of other variables like: cell, cell1, etc. After lots of improvement, i made the following.

Full code:

     var x = document.createElement("TABLE");
     x.className = "table_pos_parts";
     //var row1 = x.insertRow(0);
     //var cell1 = row1.insertCell(0);
     //var cell2 = row1.insertCell(1);
     //cell1.innerText = "abc";
     //cell2.innerText = 123;
     document.body.append(x) // add it to the document

     var y = document.createElement("TABLE");
     y.className = "table_pos_parts";
     //var row2 = y.insertRow(0);
     //var cell3 = row2.insertCell(0);
     //var cell4 = row2.insertCell(1);
     //cell3.innerText = "def";
     //cell4.innerText = 456;

     document.body.append(y) // add it to the document

You can also use document.body.insertBefore, document.body.insertAfter etc for appending it to the document.body.

Documentation: link

CodePudding user response:

seems like you haven't actually attached your newly created element into the document

  • Related