Button onclick handler breaks when JS variable and html id are the same?



I’m not an expert on JS, nor on c9.io, so I am turning to those who are. I have a simple project and this line in my html (I’m using bootstrap 4:

    <div class="col-4">   <h2 id="_score">Score: $0</h2>  </div>

I am linking in a .js file that has a let variable called score:

let score = 0 // this is not in a function

If I change id="_score" to id=“score”, it breaks my button handlers (such as the one shown here):

<button class="btn btn-warning" onclick="showQuestion('math', 200)">$200</button>

I’m not sure how to use the debugger with JavaScript in c9.io, so I can’t tell if showQuestion() is even being called, or if something in there is causing a fuss, but regardless, can a JS variable mess up an html id? That seems unlikely, but that seems to be what’s going on here.

Any advice would be appreciated!


On chrome <h2 id="score"> creates a variable named score, unless there is already another variable with that name.
Sounds like in showQuestion you are using this global variable, instead of document.getElementById('score').
It is a better practice to not rely on global variable and always use document.getElementById


Thanks for the explanation, harutyun, and the quick response.

I’m using Safari, so I guess something similar is happening here. I’d previously thought of id=" " as just a way of labeling an html element, I know now better!