David
David

Reputation: 4281

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

Upvotes: 1

Views: 533

Answers (5)

jafarbtech
jafarbtech

Reputation: 7015

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

Upvotes: 6

lahaymd
lahaymd

Reputation: 61

The element has been created, but needs to be appended to the DOM. Use the appendChild() or insertBefore() method.

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

Upvotes: 0

Rudraksh Pathak
Rudraksh Pathak

Reputation: 898

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.

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.
  • appendChild() adds your element node to DOM.

Upvotes: 0

selvakumar
selvakumar

Reputation: 654

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

Upvotes: 0

Rahul
Rahul

Reputation: 2474

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

Upvotes: 0

Related Questions