編輯: 使用這個代碼在NetBeans:如何將一個id分配給新創建的HTML元素?
var ele = document.createElement("div");
ele.id = 'tempId1';
ele.innerHTML = "TEST";
document.querySelector("body").append(ele);
document.getElementById("tempId1").innerHTML= "TEST2";
給我的錯誤:
TypeError: undefined is not a function (evaluating 'document.querySelector("body").append(ele)') (13:47:52:032 | error, javascript)
at global code (public_html/index.html:34:42)
之前appendingnull(13:47:52:036)
和此代碼:
var newElement = document.createElement("DIV");
newElement.setAttribute("id", "uniqueIdentifier");
console.log("before appending" + document.getElementById("uniqueIdentifier"));
document.body.append(newElement);
console.log("after appending" + document.getElementById("uniqueIdentifier"));
document.getElementById("uniqueIdentifier").innerHTML = "hello";
給我錯誤:
TypeError: undefined is not a function (evaluating 'document.body.append(newElement)') (13:47:52:037 | error, javascript)
at global code (public_html/index.html:51:21)
該代碼似乎在Chrome中執行正常,但在NetBeans嵌入式Webkit瀏覽器中無效。我現在想知道現在是否有其他問題,但至少我可以讓它工作。謝謝大家。
原文: (我非常不擅長編程。)
我試圖創建一個新的HTML元素,將新ID分配給它,然後調用這個ID和輸出的東西通過使用.innerHTML來放入一個字符串。
如果我使用
var newElement = document.createElement("DIV");
,然後或者:
document.newElement.id = "newId";
OR:
newElement.setAttribute("id", "uniqueIdentifier");
,然後嘗試分配文本輸出,使用新的元素:
document.getElementById("uniqueIdentifier").innerHTML = "TEST OUTPUT";
然後沒有任何反應。
我試過很多配置,但是我永遠不能使用新的id輸出任何東西。
我也複製並粘貼了人們所說的將代碼分配給新生成的對象的代碼,但是我無法使用新代碼輸出任何內容。
下面是我複製的東西的例子:
var ele = document.createElement('div');
var id = 'temp1';
ele.setAttribute('id', id);
對此我增加了一個附加行:
document.getElementById("temp1").innerHTML = "TEST";
其處於未輸出任何東西。
我試過的代碼又如:
var el = document.createElement('div'),
staticPart = 'myUniqeId',
i = 0;
el.id = staticPart + i;
el.getAttribute('id');
el.id;
對此我再次添加
document.getElementById("myUniqeId0").innerHTML = "OUTPUT TEST";
不工作。我一直堅持了幾天。提前致謝。
我認爲你缺少這裏的部分是附加新創建的元素添加到DOM。您已創建新元素,但尚未將其放置在DOM上的任何位置。您需要調用' .append(yourNewElement)'將您的新元素添加到DOM。請參閱下面的答案。 –