0

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>
realsimont
  • 32
  • 3
  • 1
    You would only be able to get the element by ID **after** you've run `addInput()`. FYI, numbers make poor `id` attribute values – Phil Nov 13 '20 at 00:19
  • 1
    Short answer, move `var personId = document.getElementById(count)` into the `test` function – Phil Nov 13 '20 at 00:20
  • @Phil adding `var personId = document.getElementById(count)` into `test` works :) thanks – realsimont Nov 13 '20 at 00:24
  • avoid `var` helps you to avoid problems as this one. Use `let` and `const`. Also you can use `window.varName` for global variables. – rzlvmp Nov 13 '20 at 00:35
  • 1
    @rzlvmp using `let` or `const` would have made absolutely no difference in this case – Phil Nov 13 '20 at 06:43
  • @Phil thank you for correction. My bad. I didn't know that `let personId` also accessible inside function. – rzlvmp Nov 13 '20 at 07:35

0 Answers0