The browser is throwing a TypeError indicating that the button is null, despite it appearing to

Would you like to create a webpage where the background color changes when a button is clicked?

There seems to be a TypeError when loading in the browser, but everything works fine when the same JavaScript code is pasted into the console.


Check out the code below:

var colors = ["#0af5fa", "#0ab1fa", "#0a3efa", "#560afa", "#b70afa", "#fa0ad9", "#fa0a65", "#fa0a1e", "#fa5e0a", "#facc0a", "#cbfa0a", "#69fa0a", "#0afa1b", "#0afa77", "#0afae5", "#0a8efa"];

var flag = 0,
  blinkCount = 0;

function blink() {
  if (blinkCount == 15) {
    blinkCount = 0;
    blink();
  } else {
    var h1 = document.querySelector("h1");
    var body = document.querySelector("body");

    h1.style.color = colors[blinkCount];
    body.style.background = colors[blinkCount];
    blinkCount++;
  }
}

var button = document.querySelector("button");
button.addEventListener("click", blink);
button {
  width: 50%;
  height: 100px;
  background: black;
  margin-top: 300px;
  margin-left: 300px;
}

h1 {
  color: #0af5fa;
}

body {
  background: #0af5fa;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<script src="../JavaScript/ex153.js"></script>
<link href="../css/ex153.css" rel="stylesheet">

<head>
  <meta charset="utf-8">
  <title></title>
</head>

<body>
  <div class="">
    <button><h1>Click Me</h1></button>
  </div>
</body>

</html>


Error Message Shown In Browser:

TypeError: button is null[Learn More]     ex153.js:25:1

Answer №1

It appears that the script is being executed before the document has finished parsing. Notice how the <script> tag is placed above the <body> and its <button> element?

To address this issue, you can either add the defer attribute to the script tag:

<script defer src="..

Alternatively, you can move the script to the bottom of the body:

    </div>
  <script src="../JavaScript/ex153.js"></script>
  </body>
</html>

Another option is to encapsulate the entire script within a DOMContentLoaded listener:

document.addEventListener('DOMContentLoaded', function() {
    var colors;
    // other code
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize the existing code to prevent multiple form submissions

My current focus is on integrating a Delete Account feature into my website. If a user requests to delete their account (please note that it takes 3 days to completely delete the data) and tries to log in within this 3-day period, we need to prompt for co ...

Determine whether the product is present, and if it is, verify whether the user is included in the array of objects

Whenever a button is clicked by a user, the system sends their userID along with the product ID to the query below. The goal is to validate if that specific product exists and then check if a particular userID exists within an array of objects in the sam ...

What is the best way to read a local text file and store its contents in a string variable within a

Within my ReactNative project, I am seeking to retrieve the content of static text files and store it in a string variable. Here is an example of how I would like to achieve this: var content = loadPlainTextFile("resources/tags.txt"); var tags = content.s ...

What is the process for customizing (adjusting color and border width) on bootstrap tabs?

https://i.sstatic.net/IdhlD.png Are you struggling with changing the color of the borders around Bootstrap tabs from light gray to dark blue? You're not alone. It can be tricky to find the right class or element to style for this specific change. Her ...

A quick demonstration of the node.js console.clear() method in action with a straightforward code snippet

Can someone provide me with a clear example of how to use the console.clear() method from the console module in node.js? I've searched extensively on stackoverflow but haven't found anything useful. console.log("Content printed in file"); con ...

Update Text in B-table Cell using Boostrap Vue

I need to change the text color of each cell in a column within a b-table. I have successfully changed the text color of the column header, but what about the individual cell texts? Here is the current b-table code: <b-card title="Total"> ...

Implementing a click event for multiple controls by utilizing class names in Angular

I have been able to successfully attach a click event in Angular using the following method: <span (click)="showInfo()" class="info-span"></span> However, I have 20 spans with similar attributes. Is there a more centralized ...

Embedding an Iframe in Angular 2 directly from the database

Looking for assistance with iframes in Angular 2. Initially, embedding an iframe directly into a component's template functions correctly. <iframe src='http://plnkr.co/edit/zZ0BgJHvQl5CfrZZ5kzg?p=preview | safeUrl' allowtransp ...

Combine going to an anchor, performing an AJAX request, and opening a jQuery-UI accordion tab all within a

My goal is to have the user click on the hyperlink below, which will (1) anchor to #suggestions, (2) navigate to the url suggestions.php?appid=70&commentid=25961, and (3) open the jquery-ui accordion #suggestions. However, I am facing an issue where c ...

The property of userNm is undefined and cannot be set

When attempting to retrieve a value from the database and store it in a variable, an error is encountered: core.js:6014 ERROR Error: Uncaught (in promise): TypeError: Cannot set property 'userNm' of undefined TypeError: Cannot set property &apos ...

Bootstrap: nav-link remains visible even after a dropdown-item is chosen

I am aiming to accomplish the following - when a dropdown-item from the navbar is selected, I want to execute BOTH of the following actions: Scroll to the div with the specified target id Collapse the navbar back to its initial state (fully rolled up, hi ...

The sidebar should remain fixed on top when viewed on mobile devices, but not when viewed on desktop

Prior to beginning a new project, I'm interested in exploring the possibility of implementing a sliding sidebar for mobile and tablets. On desktop, however, I envision a fixed sidebar that is part of the main container layout as shown below: <div ...

What could be causing the data to be displaying as undefined when using AJAX

My issue involves making an ajax call and passing an array with data. However, when I attempt to debug the code in the console, it shows that the data is undefined. What could be causing this? ...

What would be the most effective method to send an array through ajax?

My Java script array looks like this: let myArray = new Array(); myArray[0] = 'foo'; myArray[1] = 'bar'; I'm looking for the most efficient way to send this data to the server using AJAX (jQuery). Do I need to serialize it before ...

Is XMLHttpRequest just sitting idle...?

As a newcomer to the world of javascript and AJAX, I've been stuck on a single problem for the past 8 hours. Despite my best efforts, I just can't seem to figure out what's going wrong. On my website, I have an image with an onclick event ca ...

Storing JavaScript arrays in CSV format on the server

I am currently facing an issue while trying to save a multidimensional Javascript array as a CSV file on the server. Despite my efforts, the CSV file created does not seem to contain the actual array data, and I am unsure of what is causing this discrepanc ...

Steps for removing the footer from WordPress with the "powered by WordPress" message:

I am curious about how to delete the footer that says "powered by wordpress". I created this page and at the bottom of it, there is a mention of "powered by wordpress". Website ...

Is it possible to utilize the defineProperty accessor in JavaScript to modify the .length property of an array?

I am interested in setting an accessor on an array's length using Object.defineProperty() for academic purposes. This would allow me to notify for size changes dynamically. While I am familiar with ES6 object observe and watch.js, I prefer exploring ...

What is the best way to keep track of dynamically inserted input fields?

I've created a form with two text boxes: one for entering people's "name" and another for their "surname." By clicking on the page, you can add additional pairs of text boxes for both "name" and "surname," allowing users to input as many pairs as ...

What is the solution to the error "Maximum update depth exceeded. Calls to setState inside componentWillUpdate or componentDidUpdate" in React?

Everything was running smoothly until this unexpected issue appeared. I attempted to change the condition to componentDidMount, but unfortunately, that didn't resolve the problem. The error is occurring in this particular function. componentDidUpd ...