JavaScript getElementById returns null

getelementbyid, javascript

Solution

Try using `parseInt`:

var nextDiv = document.getElementById('div-'+parseInt(counter+1,10));

The parseInt function converts its first argument to a string, parses it, and returns an integer.The second arguement is radix which is "base", as in a number system.

Demo

Problem

I'm learning JavaScript and I'm wondering why something like: `document.getElementById('partofid'+variable+number)` doesn't work? Here are samples and JSfiddle link, I want "next" button to remove displayed item and show the next one. HTML: ``` <div id="div-1"> 1 </div> <div id="div-2" style="display: none"> 2 </div> <div id="div-3" style="display: none"> 3 </div> <div id="div-4" style="display: none"> 4 </div> <a id="next" href="#">next</a> ``` JS: ``` var counter = 1; var button = document.getElementById('next'); button.addEventListener("click",function(){ var currentDiv = document.getElementById('div-'+counter); currentDiv.remove(); var nextDiv = document.getElementById('div-'+counter+1); alert(nextDiv); // why does it return null alert('div-'+counter+1); // while this doesn't? nextQuestion.style.display = "block"; counter++; },true); ```

Original source