2

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.

0

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

2 Comments

It still doesn't work for me. It still thinks that the element is null.
Nevermind, I got it to work. I just had to put the script tag at the end of the body instead of the head.
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.