![](/img/trans.png)
[英]TypeError: document.getElementById(…) is null Django + JS
[英]document.getElementById giving Null by JS not by HTML
當我在 html 中定義我的輸入標簽並通過 id 在 JS 中訪問時,我得到了我的標簽。
HTML代碼:
<input class="easyui-combobox" name="language" style="width:30%;" id= "XX">
JS代碼:
var cc = document.getElementById("XX");
這里一切都很好。
但是當我從 javascript 創建並嘗試訪問時,我得到了。 我想要動態所以我需要從 JS 創建。
JS代碼:
var input = document.createElement("input");
input.className = 'easyui-combobox';
input.style = 'width:30%';
input.id = "XX";
在這里,我在應用此后得到空值:
var cc = document.getElementById("XX");
您必須使用document.body.appendChild(input);
將創建的元素附加到文檔中document.body.appendChild(input);
var input = document.createElement("input"); input.className = 'easyui-combobox'; input.style = 'width:30%'; input.id = "XX"; document.body.appendChild(input); console.log(document.getElementById("XX"));
你還沒有附加你的元素
var input = document.createElement("input");
input.className = 'easyui-combobox';
input.style = 'width:30%';
input.id = "XX";
document.body.appendChild(input);
var cc = document.getElementById("XX");
console.log(cc);
您需要將輸入元素附加到文檔
var input = document.createElement("input");
input.className = 'easyui-combobox';
input.style = 'width:30%';
input.id = "XX";
document.body.appendChild(input);
您已經使用 - 創建了您的元素
var input = document.createElement("input");
現在您需要將它附加到 HTML 以便您可以在 DOM 上找到它。
var input = document.createElement("input"); input.className = 'easyui-combobox'; input.style = 'width:30%'; input.id = "XX"; document.body.appendChild(input); var fetchedElement = document.getElementById("XX"); console.log(fetchedElement);
createElement()
創建一個元素節點。appendChild()
將您的元素節點添加到 DOM。
元素已創建,但需要附加到DOM 。 使用appendChild()
或insertBefore()
方法。
var input = document.createElement("input");
input.className = 'easyui-combobox';
input.style = 'width:30%';
input.id = "XX";
document.body.appendChild(input);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.