2017-06-09 75 views
1

當我在html中定義我的輸入標記並通過id訪問JS時,我得到我的標記。document.getElementById由JS而不是HTML給予NULL

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

回答

5

你有你創建的元素追加到使用文檔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"));

+0

是在身體附加是正確的。謝謝 – David

0

您沒有附加的元素

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); 
0

您需要添加輸入元素來記錄

var input = document.createElement("input"); 
input.className = 'easyui-combobox'; 
input.style = 'width:30%'; 
input.id = "XX"; 
document.body.appendChild(input); 
0

您已經創建使用你的元素 -

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。
0

的元件已被創建,但需要附加到DOM。使用 appendChild()insertBefore()方法。

var input = document.createElement("input"); 
input.className = 'easyui-combobox'; 
input.style = 'width:30%'; 
input.id = "XX"; 
document.body.appendChild(input); 
相關問題