There was an unexpected TypeError when attempting to access the property 'firstElementChild' of a null value

Attempting to execute the code.

Steps:

Click on any option --> click No, I am not sure --> Click on any option --> click Yes, lock the option

The second time button (Yes, lock the option) will not perform any action, and an error was found in the console:

Uncaught TypeError: Cannot read property 'firstElementChild' of null

Visit this link for live demo

Answer №1

There are a couple of issues in your code that need to be addressed. One problem is related to the selection variable, which should be declared outside of the onSelect function. Another issue is that you are binding the jQuery.click() event to buttons every time the onSelect() function is called. Consider moving the event handler outside of the function and also declaring the selection variable separately.

 var selection;
 var currentQuestion;

function onSelect(e) {
  selection = e.currentTarget;
  var questionId = e.currentTarget.className;
  currentQuestion = questions.find(function(q) {
    return q.questionId == questionId
  }); 
   $("#myModal").modal();
   document.getElementById("m_q").innerHTML = "<h3>" + currentQuestion.question + "</h3>";
   document.getElementById("m_o").innerHTML = "<h2>" + selection.firstElementChild.innerText + "</h2>";



}
     $("#myBtnC").click(function(){
        //onConfirm(e);

        selection.setAttribute('class', 'question1');
        selection = null;
        $('#myModal').modal('hide');
    });

    $("#myBtnO").click(function(){

        if (currentQuestion.locked) {
            alert("Question already answered");
        } 
        else if (currentQuestion.answer === selection.firstElementChild.innerText) {
            alert("Correct!!!");
        } else {
            alert("Incorrect...");
        }
        //generateQuestion(questions[i]);


        $('#myModal').modal('hide');
    });

Answer №2

Eliminate the null value for "selection" in relation to #myBtnC. Remove this segment from your code.

Implement this adjustment and inform me of any results.

function onSelect(e) {
    var selection = e.currentTarget;
    var preSelection = selection;
    var questionId = e.currentTarget.className;
    var currentQuestion = questions.find(function(q) {
        return q.questionId == questionId
    });
    $("#myModal").modal();
    document.getElementById("m_q").innerHTML = "<h3>" + currentQuestion.question + "</h3>";
    document.getElementById("m_o").innerHTML = "<h2>" + selection.firstElementChild.innerText + "</h2>";

    $("#myBtnC").click(function() {
        
        if (!selection) {
            selection = preSelection;
        }

        selection.setAttribute('class', 'question1');
        selection = null;
        $('#myModal').modal('hide');
    });

    $("#myBtnO").click(function() {

        if (currentQuestion.locked) {
            alert("Question already answered");
        }

        if (!selection) {
            selection = preSelection;
        } else if (currentQuestion.answer === selection.firstElementChild.innerText) {
            alert("Correct!!!");

        } else {
            alert("Incorrect...");

        }
        selection = null;
        $('#myModal').modal('hide');
    });
}

This revised version functions optimally. Customize it as needed based on your specifications.

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

Having trouble with spawning child processes asynchronously in JavaScript

I'm trying to figure out how to format this code so that when a user clicks a button, new input fields and redirect buttons are asynchronously inserted into the unordered list. Everything was working fine until I added the redirect button insertion fu ...

Download function in Express.JS failing to retrieve file

I have been working on a Node.JS server using Express to generate and download PDFs based on user input. Previously, I used the <form action=""> method to call my API, but switched to Axios due to Netlify not supporting NuxtAPI. The program ...

What is the reason behind BeautifulSoup continually reminding me to upgrade my browser?

Trying to extract the leaderboard table from the PGA Tour website using bs4. As a newcomer to HTML and Python, I have been following tutorials with sample websites where everything works fine. However, when I attempt to run the following code: from bs4 imp ...

Creating a basic JSON array using the push method

When adding comments to a blog post using the line: blogpost.comments.push({ username: "fred", comment: "Great"}); The JSON structure of the comments section will look like this: "comments":[{"0":{"username":"jim","comment":"Good",},"1":{"username":"fre ...

Creating a straightforward HTML output using jQuery and JSON

Currently, I am teaching myself how to handle data flow from mySQL to PHP to JSON/JavaScript, but I seem to be stuck at this particular stage. My goal is to loop through external JSON data and display it in an unordered list. Despite attempting to modify t ...

"Using the fetch Prototype.json() method can lead to the alteration or corruption of the

For the past week, I've been struggling with a seemingly impossible issue in my Javascript code: The problem arises when trying to retrieve data from the server using fetch: fetch(this.props.url, { method: 'POST', b ...

Improving CSS performance in React Styled Components

Which method is more efficient and why? I have heard that the css method in Styled-components can be resource-intensive. I am curious to know if using multiple nested ${(prop) => {}} functions is more costly compared to a single function with the css m ...

Eliminate a specific array from the firebase database

If I click on the delete button for item2, I want it to be removed from the list. { "items" : { "category1" : { "item" : { "0" : { "name" : "item1", }, "1" : { "name ...

Initial Year Setting for MUI X datepicker

For a project I am working on with my client, they have requested that the datepicker in MUI X default to the year 2023. They would like the datepicker to automatically display the year 2023 with the option for them to change it if needed, as most of the d ...

Using mongoDB to insert data followed by processing it with the process.next

Currently, I am in the process of inputting a list of 50k entries into my database. var tickets = [new Ticket(), new Ticket(), ...]; // 50k of them tickets.forEach(function (t, ind){ console.log(ind+1 + '/' + tickets.length); Ticket.find ...

The issue of not being able to add data to the client is encountered in a local setup involving Socket.io, MSSQL

I have a large dataset that needs to be retrieved from a SQL server using Node.js and then broadcasted to clients in real-time using Socket.IO. I've been successful in fetching the data, but the UI on the client side isn't updating. Although I c ...

Preventing the automatic selection of the initial item in a PrimeNG dropdown menu

While utilizing the p-menu component from PrimeNG in popup mode ([popup]="true"), I encountered an unexpected issue where the first item in the menu is automatically selected and turns gray. Here is the code snippet that I am using: <p-menu #menu [popu ...

Generating dynamic JSON arrays to create multiple data tables

I need to generate multiple datatables for each jsonobject [which represents weekly attendance data] in the jsonarray. By making an ajax request, I am retrieving the JSON Array from Java. Can someone guide me on how to create multiple datatables for each ...

Exploring the integration of session authentication and jQuery within Drupal 7 Services 3.4

I am facing a challenge in connecting Drupal 7 with jQuery using Services 3.4 and the jQuery cookie plugin. To accomplish this, I need to follow these steps: - post to the service endpoint /user/login - retrieve session name and session id and set them a ...

retrieve the chosen option from the dropdown menu

Whenever I try to display the input type based on the selection from a select element, I encounter an issue Here is the select element within my view: <select id="type" name="type_id" class="form-control" required> @foreach($type as $row) & ...

Is there a way to enable drag and drop functionality on a dynamically created table using AJAX?

I have been successfully using the TableDnD plugin for drag and drop functionality on table rows. However, I am now facing an issue with dynamically generated tables via AJAX. The code doesn't seem to work as expected when it comes to drag and droppin ...

What is the method for showcasing background images sequentially?

css code #intro { position: relative; background-attachment: fixed; background-repeat: no-repeat; background-position: center top; -webkit-background-size: cover; -moz-background-size: cover; backgr ...

Using JQuery to attach a click event to a div element

My HTML code looks something like this: <div class="vmail vmail-bar normal-vmail-bar" id="pm_<?php echo $pm->to_id; ?>"> <div class="checkbox"><input type="checkbox" class="checkbox" /></div> ...

What is preventing Backbone from triggering a basic route [and executing its related function]?

Presenting My Router: var MyRouter = Backbone.Router.extend({ initialize: function(){ Backbone.history.start({ pushState:true }); }, routes: { 'hello' : 'sayHello' }, sayHello: function(){ al ...

What is the easiest method to preserve a specific dd option when submitting a form?

My webform has validation functions for each field, and if there are any validation failures when the form is submitted, the user is returned to the form with previous values in the input fields and error messages displayed. This functionality is working c ...