HeadFirst Battleship App Challenges

var view = {
        displayMessage: function(msg) {
            var messageArea = document.getElementById("messageArea");
            messageArea.innerHTML = msg;
        },
        displayHit: function(location) {
            var cell = document.getElementById(location);
            cell.setAttribute("class", "hit");
        },
        displayMiss: function(location) {
            var cell = document.getElementById(location);
            cell.setAttribute("class", "miss");
        }
    };

view.displayMiss("00");
view.displayHit("34");
view.displayMiss("55");
view.displayHit("12");
view.displayMiss("25");
view.displayHit("26");

view.displayMessage("Tap, tap, is this thing on ?");

I have been working on this code and it keeps giving me this error :
Uncaught TypeError: Cannot read property ‘setAttribute’ of null
at Object.displayMiss (battleship1.js:13)
at battleship1.js:17

Any suggestions or corrections will be welcome, as I just started learning JavaScript this year. Many thanks in advance…

It can’t find an element with the ID you’re trying to select, so the value of cell is null. Because it is null, and null does not have a method setAttribute (or any methods at all for that matter), you get a type error

So what do I do now ? Do I just keep learning until the ID is given ?

Thanks so much for taking the time to respond to my message. Its really appreciated. Thank you.

What do you mean? What is happening is that there’s literally not an element with that ID, you can’t select something that doesn’t exist. The solution is to select something that does exist.

Like if you have some HTML that looks like this

div
  div#1
  div#2
  div#3

You can’t select the div with the ID of 4 because there isn’t a div with an ID of 4. There are only divs with IDs of 1, 2 and 3.


If you are generating the cells with JS, then there may be a flaw in your logic — ie you are trying to select cells you have created before they have been created. But I can’t tell that from the code you have here.