Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript getElementById returns null

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);
like image 231
Wordpressor Avatar asked Mar 29 '26 23:03

Wordpressor


1 Answers

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

like image 81
Joke_Sense10 Avatar answered Apr 02 '26 10:04

Joke_Sense10



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!