What could be causing the JavaScript error in this code snippet?

Check out this code snippet:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>My Cool App</title>

  </head>
  <body>
    <p id='nameDisplay'> Name Display Area </p>
    <button id="showBtn" type="button">Show Names</button></br>
    <button id="likeBtn" type="button">Like</button>
    <button id="dislikeBtn" type="button">Dislike</button>

  </body>

  <script type="text/javascript" src="http://code.jquery.com/jquery-1.12.1.min.js"></script>
  <script>
  $(document).ready(function(){
  var names = ['John', 'Emily', 'Alex', 'Grace', 'Liam'];
  var likedNames = [];
  var dislikedNames = [];



    function displayNextName (){
      var currentName = names[0];
      if (!currentName){
        currentName = 'No more names to show';
      }
      document.getElementById('nameDisplay').innerHTML = currentName;
    }

    function likeAction(){
      likedNames.push(names[0]);
      names.splice(0, 1);
      displayNextName();
    }

    function dislikeAction(){
      dislikedNames.push(names[0]);
      names.splice(0, 1);
      displayNextName();
    }

    displayNextName();
    document.getElementById('likeBtn').onclick = likeAction;
    document.getElementById('dislikeBtn').onclick = dislikeAction;

 });
  </script>
</html>

The error message currently displayed is:

uncaught TypeError: Cannot set property 'onclick' of null

I did some research on this error and it seems to be related to the DOM, possibly indicating that elements have not been fully loaded onto the page yet?

The desired functionality is for different names to appear each time the user clicks the like or dislike button until all names have been displayed.

Answer №1

The unique identifier for your button is likebutton and you are selecting it using the code likeButton

Modify

document.getElementById('likeButton').onclick = like;

Into

document.getElementById('likebutton').onclick = like;

The same behavior applies to dislikebutton.

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

Flashing Effect of Angular Ui-Bootstrap Collapse During Page Initialization

Below is the code snippet I've implemented to use the ui-bootstrap collapse directive in my Angular application. HTML: <div ng-controller="frequencyCtrl" style="margin-top:10px"> <button class="btn btn-default" ng-click="isCollapsed = ...

Retrieve the complete line of text from both a textarea and an editable div

When I right-click inside a textarea, the entire line regarding the current cursor position is displayed. I am trying to achieve the same with an editable div, but it's not working. The console is empty, showing an empty string. Can someone please hel ...

Using selenium for testing JavaScript elements through RSpec results in failures in other segments of the RSpec test

Trying to implement Stripe into my web application has brought me to a frustrating roadblock. Every attempt to test the "Pay with Card" button seems to be thwarted by an ElementNotFound error thrown by rspec. Research revealed that the root cause of this ...

Using useState props in React Native navigation screens with React Navigation

I'm currently working on my first React Native app with react navigation after previously having a background in web react development. In the past, I typically used useState for managing state. For instance, rendering a list of components based on d ...

Exploring the Concept of Template Element Recursion in Angular JS 2

In my Angular 2 project, I encountered a situation where I needed to iterate through ngFor based on child elements. My component should be able to render a list based on the input provided. Here is an example of the data structure: [ { name: 'ABC ...

A React component utilizing dangerouslySetInnerHTML and including CSS styles

One of my React components displays the following element: <div dangerouslySetInnerHTML={{__html: this.props.htmlString}}/> While the html renders correctly, I am facing a challenge with my client-side CSS code affecting the component I am renderin ...

Developing desktop applications using C# scripting

I currently have a C# desktop program that is able to work with new C# plugins. My goal is to modify the existing C# application to allow for scripts to be used as plugins. These scripts could be in JavaScript, Windows Script Host (WSh), or any other form ...

Text input appearing on top of each other within the multiline TextField component in Material-UI

I'm experiencing an issue where the input text in a Material-UI Multiline TextField is overlapping. It seems to happen when I increase the font size to 30 but the line-height or some other factor remains set for the default font size. For reference ...

The Express error is thrown when attempting to read the property 'get' of an undefined value

Currently in the process of organizing my routes in a separate directory: server.js: var express = require("express"), parse = require("body-parser"), db = require("mysql"), mailer = r ...

"The authentication scheme is unrecognized" - this is the message produced by Node-LinkedIn module

I am currently utilizing the node-linkedin npm package to authenticate and retrieve information about other users, such as their name, job title, company name, profile picture, and shared connections. While I am able to successfully receive and store the a ...

Looking for a specific text on $location update in AngularJS

Is there a way in AngularJS to search the DOM for text after a new view is loaded? The filter almost does this, but I'm not interested in returning a new array of elements. For instance; html <div ng-view=""> <ul> &l ...

Retrieve initial elements from an array with the help of Node.js or JavaScript

let array = [[`animal`,`carnivours`], [`cow`,`milk`], [`plant`,`small`], [`fish`,`tank`]] console.log(array[0]); It seems that when trying to retrieve the first value from an array, we typically use array[0] to access all the first elements in the a ...

Having issues with the POST method in node.js and express when connecting to a MySQL database

My GET method is functioning perfectly I have a database called stage4 and I am attempting to insert values into it from a frontend page The connection is established, I'm using Postman to test it first, but it keeps returning a "404 error" which is ...

Is it possible to trigger a keydown event using a forEach loop?

I've been working on implementing an accessibility feature for a bootstrap accordion. I included the tabindex=0 in each <a> tag in an attempt to make it so that when the user presses the tab key, it opens the corresponding dropdown/accordion. Ho ...

Tips for combining multiple lists into a single dictionary using a specific key in Python

I have multiple lists with related elements and I am looking to consolidate them into a single dictionary where the lists serve as values: list1 = ['cat', 'animal'] list2 = ['dog', 'animal'] list3 = ['crow&apos ...

Strategies for integrating a username-only login using Firebase without requiring a password or email address

For my class assignment, I'm developing a webapp and want to implement a login system with only a username. However, when I try sending just the username to the database, it gets stored as a child under the connection ID in Firebase. Below is the Java ...

Utilizing JavaScript to implement an interactive :hover pseudo-class dynamic effect

After reviewing a question on adding a hover class to an element, I am now curious about how to do the opposite. I already have a main class for a button I am planning to create, where I will customize the background for each button using myButton.style.b ...

SQL's ISJSON function is returning false when using JSON.stringify. It seems

I'm on a quest to understand why this specific data is not being recognized as JSON within SQL. It's being sent from the front end using JSON.stringify. '[{\"value\":\"TB12\",\"label\&qu ...

Tips for reducing the output value using jQuery

Hey there, I am displaying a value using jQuery and would like to reduce the decimal places. The current value being shown is: 6.333333333333333 I want it to be displayed like this instead: 6.3 Does anyone know how to achieve this? I couldn't ...

Encountering the error message ERR_CONNECTION_TIMED_OUT while using Vue CLI

Currently, I am venturing into the world of Vuex and attempting to incorporate some API requests using this state management pattern. Here is the structure I have set up: Component.Vue export default { created() { this.$store.dispatch('getDat ...