Reputation: 47
I don't know why I am getting this error. I think I have closed every bracket.
I tried making the id letters instead of numbers.
function check(x,y) {
coor = "'" + x + y + "'";
if (document.getElementById(coor).classList.contains("bomb")) {
document.getElementById('WoL').innerHTML = "You lose.";
}
}
HTML:
<div class = "grid-square" onclick = "check(1,8)" id = "18">?</div>
I expect the output to make the paragraph with id "WoL" say "You lose." if you click on the div and it is a bomb.
Upvotes: 2
Views: 814
Reputation: 469
function check(x,y) {
coor = x.toString() + y.toString();
if (document.getElementById(coor).classList.contains("bomb")) {
document.getElementById('WoL').innerHTML = "You lose.";
}
}
check(1,1);
<div id="WoL"></div>
<div class="bomb" id="11">A tile containing a bomb</div>
Upvotes: 1
Reputation: 50844
You're wrapping your string in quotes, and so, at the moment you are really looking for an element with the id of '18'
not 18
(thus giving you null
). Instead, you can either concatenate x
and y
with an empty string or use the String()
method to convert your numbers into a string.
You'll also need to add the class bomb
to your div to pass your if
statement check.
Lastly, you need to ensure that you are targetting the correct element to change the HTML of document.getElementById('WoL')
isn't an element in your HTTML and thus won't do anything.
See example below:
function check(x, y) {
var coor = ''+x + y;
var target = document.getElementById(coor);
if (target.classList.contains("bomb")) {
target.textContent = "You lose.";
}
}
<div class="grid-square bomb" onclick="check(1,8)" id="18">?</div>
Upvotes: 0