Riadan414 Riadan414 - 6 months ago 18
Javascript Question

.innerHTML: Cannot set property 'innerHTML' of null

First, I am completely new to coding and have been using self-teaching tools to learn Javascript in my free time. I've learned enough to start building my own projects. My first attempt is to build a randomizer (in this case, random restaurant names). The Javascript works through my tests in the console as do the buttons. However, I cannot seem to get the .innerHTML to work and I'm not sure what I'm missing. I've done several searches here and none of the solutions I've found seem to be working.

The error I'm getting is listed in the title and it is appearing at line 29.

Here is Javascript:

var randomRestaurant = {
restaurantName: [],
findRestaurant: function() {
var restaurantName = Math.random();
if (restaurantName < 0.20) {
this.restaurantName.push("China Taste");
}
else if (restaurantName < 0.40) {
this.restaurantName.push("Pizza Johns");
}
else if (restaurantName < 0.60) {
this.restaurantName.push("Liberatore's");
}
else if (restaurantName < 0.80) {
this.restaurantName.push("Bill Bateman's");
}
else {
this.restaurantName.push("R&R Taqueria");
}
},
clearRestaurant: function() {
randomRestaurant.restaurantName.splice(0, 1);
}
};

var randomRestaurantButton = document.getElementById('randomRestaurantName');
randomRestaurantButton.addEventListener('click', function() {
randomRestaurant.findRestaurant();
document.getElementById("restaurantNameDisplay").innerHTML = randomRestaurant.restaurantName[0]; //<--line 29
});

var randomRestaurantButton = document.getElementById('refreshRestaurant');
randomRestaurantButton.addEventListener('click', function() {
randomRestaurant.clearRestaurant();
randomRestaurant.findRestaurant();
document.getElementById("restaurantNameDisplay").innerHTML = randomRestaurant.restaurantName[0];
});


And here is my HTML:

<!DOCTYPE html>
<html>

<head>
<link rel="stylesheet" href="style.css">

</head>

<body>
<div><h1>Random Restaurant!</h1>

<button id="randomRestaurantName">Click me for a random restaurant!</button>
</div>
<br>

<h2="restaurantNameDisplay"></h2="restaurantNameDisplay">

<div>
<br>
<button id="refreshRestaurant">Nah. Give me another one.</button>
</div>

</body>
<script src="script.js"></script>
</html>


Thanks for your help and hopefully it's not due to something stupid like a typo.

Answer

Most probably this line <h2="restaurantNameDisplay"></h2="restaurantNameDisplay"> should be <h2 id="restaurantNameDisplay"></h2>

Comments