I keep getting 'null' returned when I try to getElementById on an element created by JS, even though the created element does have an id assigned to it (have tested this).
I have one button which calls a function to create text inputs on the page, and each new input is assigned an id of a number starting from 1 and incrementing up by 1 each time I click 'add input'. e.g. id="1", id="2", id="3" etc. This works.
Then I want to call a second function with a button, test, which gets the most recently added input id by it's name (which is a number e.g. 1 or 2 or 3 etc.) and logs to the console. This always returns null, even after I have added multiple inputs which do have id's. Here is my code:
<button id="add-input" onclick="addInput()">Add Input</button>
<button id="test" onclick="test()">Test</button>
<div id="main-div"></div>
<script>
//create input and assign id of a number, 'count' - this works
var count = 0;
var newInput;
function addInput() {
count++;
newInput = document.createElement("input");
newInput.type = "text";
newInput.id = count;
newInput.name = "Person " + count;
newInput.placeholder = "Person " + count;
//append to main-div
var mainDiv = document.getElementById("main-div");
mainDiv.appendChild(newInput);
}
//get the element by id and log it to console - returns null
var personId = document.getElementById(count);
function test() {console.log(personId)}; //returns null
</script>