[英]Why is getElementsByClassName not working for dynamically created HTML elements?
我正在創建多個動態 HTML 表,並為它們分配 class。 像這樣:
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;
現在,當我使用console.log(x)
時,我可以在控制台中看到所有表,但是當我開始按類名搜索它們時:
console.log(document.getElementsByClassName("table_pos_parts")); //shows empty
console.log(document.getElementsByClassName("table_pos_parts").length); //prints 0
它顯示為空。 為什么?
使固定:
您沒有將x
添加到document.body
,要解決此問題,請使用document.body.append(x)
然后在控制台中您會得到它。
改進:另外,您的 var x 使用了兩次,這意味着 x 將記錄附加的最后一個元素,如果稍后您想更改它,則不能。 要修復它,只需將第二個元素的變量名稱更改為其他名稱(但不能稱為“x”)以及其他變量的名稱,例如:cell、cell1 等。經過大量改進,我做了以下。
完整代碼:
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
您還可以使用document.body.insertBefore
、 document.body.insertAfter
等將其附加到document.body
。
文檔:鏈接
似乎您實際上還沒有將新創建的元素附加到文檔中
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.