繁体   English   中英

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

[英]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.

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