Riadan414 Riadan414 - 1 year ago 61
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) {
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() {
document.getElementById("restaurantNameDisplay").innerHTML = randomRestaurant.restaurantName[0]; //<--line 29

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

And here is my HTML:

<!DOCTYPE html>

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


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

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


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

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

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

Answer Source

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