简体   繁体   English

document.getElementById 通过 JS 而不是 HTML 给出 Null

[英]document.getElementById giving Null by JS not by HTML

When I am defining my input tag in html and accessing in JS by id then I am getting my tag.当我在 html 中定义我的输入标签并通过 id 在 JS 中访问时,我得到了我的标签。

HTML Code: HTML代码:

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

JS Code: JS代码:

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

Here things are fine.这里一切都很好。

But When I am creating from javascript and trying to access I am getting.但是当我从 javascript 创建并尝试访问时,我得到了。 I want dynamic So I need to create from JS.我想要动态所以我需要从 JS 创建。

JS Code: JS代码:

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

Here I am getting null after applying this:在这里,我在应用此后得到空值:

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

You have to append your created element into the document using document.body.appendChild(input);您必须使用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"));

You have not appended your element你还没有附加你的元素

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

You need to append input element to document您需要将输入元素附加到文档

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

You have created your element using -您已经使用 - 创建了您的元素

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

Now you need to append it to HTML so that you can find it on DOM.现在您需要将它附加到 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() creates an Element Node. createElement()创建一个元素节点。
  • appendChild() adds your element node to DOM. appendChild()将您的元素节点添加到 DOM。

The element has been created, but needs to be appended to the DOM .元素已创建,但需要附加到DOM Use the appendChild() or insertBefore() method.使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM