2017-06-09 3 views
1

Wenn ich meine Eingabe-Tag in HTML und den Zugriff in JS durch ID definieren, dann bekomme ich mein Tag.document.getElementById geben Null von JS nicht von HTML

HTML-Code:

<input class="easyui-combobox" name="language" style="width:30%;" id= "XX"> 

JS-Code:

var cc = document.getElementById("XX"); 

Hier sind die Dinge in Ordnung.

Aber wenn ich von Javascript erstelle und versuche, Zugang zu bekommen, bekomme ich. Ich möchte dynamisch Also muss ich von JS erstellen.

JS-Code:

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

Hier erhalte ich diese nach der Anwendung von null:

var cc = document.getElementById("XX"); 

Antwort

5

Sie haben Ihr erstelltes Element in die 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"));
mit Dokument anhängen

+0

Ja an Körper anfügen ist korrekt. Vielen Dank – David

0

Sie haben Ihr Element nicht

beigefügten
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

Sie müssen Eingabeelement anhängen dokumentieren

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

Sie Ihr Element mit erstellt haben -

var input = document.createElement("input"); 

Jetzt müssen Sie um es an HTML anzuhängen, damit Sie es im DOM finden können.

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() erzeugt einen Elementknoten.
  • appendChild() fügt Ihren Elementknoten zu DOM hinzu.
0

Das Element erstellt wurde, sondern muss auf den DOM angehängt werden. Verwenden Sie die Methode appendChild() oder insertBefore().

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