Skip to content
Advertisement

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 Code:

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

JS Code:

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

Here things are fine.

But When I am creating from javascript and trying to access I am getting. I want dynamic So I need to create from JS.

JS Code:

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

Advertisement

Answer

You have to append your created element into the document using 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"));
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement