What is causing the #reset button to trigger the Flow.reset() function when the #gameboard does not contain any child elements?

Whenever I click on the resetBtn, it triggers the Flow.reset function regardless of whether the gameboard has child elements. Am I using the hasChildNodes() method incorrectly?

const resetBtn = document.querySelector('#reset');
resetBtn.addEventListener('click', () => {
  if (document.getElementById('gameboard').hasChildNodes()) {
    Flow.reset();
   } 
  else {
    return;
  }
});

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" type="text/css" href="styles.css">
    <script src="main.js" type="text/javascript"></script>
    <title>Tic Tac Toe</title>
</head>
<body>
    <div class="mainContainer">
        <h1 class="header">Tic Tac Toe</h1>
        <div class="gameBoard" id="gameboard">

        </div>
        <div class="names-container">
            <input type="text" id="player1" placeholder="Player 1 Name">
            <input type="text" id="player2" placeholder="Player 2 Name">
        </div>
        <div class="buttonsContainer">
            <button class="startBtn" id="start" class="name-field">Start</button>
            <button class="resetBtn" id="reset" class="name-field">Reset</button>
        </div>
        <div class="message"></div>
        <div class="resultsContainer"></div>
    </div>
</body>
</html>

Answer №1

Your HTML code has an issue where the extra line within the div creates a childNode.

The following code snippet evaluates to true, as there is text between the <div> tags:

console.log(document.getElementById('gameboard').hasChildNodes())
<div class="mainContainer">
    <h1 class="header">Tic Tac Toe</h1>
    <div class="gameBoard" id="gameboard">

    </div>
    <div class="names-container">
        <input type="text" id="player1" placeholder="Player 1 Name">
        <input type="text" id="player2" placeholder="Player 2 Name">
    </div>
    <div class="buttonsContainer">
        <button class="startBtn" id="start" class="name-field">Start</button>
        <button class="resetBtn" id="reset" class="name-field">Reset</button>
    </div>
    <div class="message"></div>
    <div class="resultsContainer"></div>
</div>

If you remove the empty lines within the tags, it will return false and function as intended.

console.log(document.getElementById('gameboard').hasChildNodes())
<div class="mainContainer">
    <h1 class="header">Tic Tac Toe</h1>
    <div class="gameBoard" id="gameboard"></div>
    <div class="names-container">
        <input type="text" id="player1" placeholder="Player 1 Name">
        <input type="text" id="player2" placeholder="Player 2 Name">
    </div>
    <div class="buttonsContainer">
        <button class="startBtn" id="start" class="name-field">Start</button>
        <button class="resetBtn" id="reset" class="name-field">Reset</button>
    </div>
    <div class="message"></div>
    <div class="resultsContainer"></div>
</div>

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

Unexpected server failure when connecting via socket.io to Node.js http-proxy

I'm encountering an issue with my Nodejs proxy server related to the dreaded socket hang up error. The server crashes every time I refresh the browser on 'app.example.com'. The connection seems fine and the page loads correctly, but the cra ...

Having trouble making the menu stay at the top of the page in IE7

Check out the demo here: http://jsfiddle.net/auMd5/ I'm looking to have the blue menu bar stay fixed to the top of the page as you scroll past it, and then return to its original position when scrolling back up. This functionality works in all brows ...

How can I allow users to select multiple files with just one input?

Currently, I am able to retrieve a single file from a single input using the following code: $scope.$on("fileSelected", function (event, args) { $scope.$apply(function () { $scope.files.push(args.file); ...

When utilizing an object as state in React, the `setState` function will only set

Currently, I am working on developing a React form that utilizes a custom Input component which I have created multiple times. The objective is to gather all the names and values from the form in the parent component: {inputName: value, inputName2: valu ...

What is the best way to align a div right below an image that has been clicked on?

I am designing a website that features social media icons spread out horizontally across the page. When a user clicks on one of these icons, I envision a pop-up window appearing below it, displaying additional information. Here is a visual representation o ...

Leveraging batchWriteItem with dynamodb

I am trying to utilize batchWriteItem in my DynamoDB to add data to two tables: candidate table and user table. The formatted query is shown below: var user = { userid: usrid, role: 'candidate', password: vucrypt.encryptp ...

Strip away double quotation marks from object attributes except those beginning with a number

I've searched extensively and reviewed various Q&A forums, but I haven't encountered a scenario quite like this. Here's an example of the object I'm working with: props: { "label": "1rem", "text3": "1rem", "text2Button": "1re ...

In AngularJS, the use of the '+' operator is causing concatenation instead of addition

Looking for assistance with my TypeScript code where I've created a basic calculator. Everything is working as expected except for addition, which seems to be concatenating the numbers instead of adding them together. HTML CODE : <input type="tex ...

Error: The property 'slice' cannot be read from an undefined value

I am currently working on a prototype recipe app called Forkify, which is being developed using Javascript, NPM, Babel, and Webpack. In this project, I am utilizing a custom API. API URL : forkify-api.herokuapp.com TO SEARCH RESULT This API returns a l ...

Search for a specific folder and retrieve its file path

Is there a way for me to include an export button on my webpage that will allow users to save a file directly to their computer? How can I prompt the user to choose where they want to save the file? The button should open an explore/browse window so the ...

Trouble embedding iframes in local files?

I have recently created a file which includes the following code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8> <style> iframe { height: 500px; width: 600px; } ...

Importing WebAssembly dynamically can sometimes lead to complications with the order of execution

I am attempting to load a WASM library from another node js application, both utilizing webpack. Within the WASM library, I have the following code snippet exporting the functionality. export default import("./pkg") .then(s => { le ...

ReactJS: Checkbox status remains consistent through re-rendering of Component

I have developed a JSfiddle example Initially, this fiddle displays a list of checkboxes based on the passed props to the component. When you click the Re-render button, the same component is rendered with different props. Now, please follow these steps- ...

Issue encountered when trying to import @tensorflow/tfjs-node in conjunction with the face-api.js library within a node.js environment

Using the @tensorflow/tfjs-node package along with face-api.js to enhance performance, here is my code snippet: // Import nodejs bindings to native tensorflow, // Not required but will significantly speed up operations (Python required) require('@tens ...

The console is displaying a promise that is pending, rather than the desired data

Here is the content of my file: 'use strict' import * as moment from "moment"; import { Report} from "./Report"; import { Timeframe} from "./Timeframe"; import { ReportComparison } from "./ReportComparison"; function test(firstFrom: string, fi ...

Tips on how to display a Vue component on a new page with Vue.js router

My current challenge is getting my App to render on a new page instead of the same page. Despite trying render: h => h(App), it still renders on the same page. This is the Vue file (Risks.vue) where the router will be linked: <router-link to="/risk ...

How can I turn off shadows for every component?

Is it feasible to deactivate shadows and elevation on all components using a configuration setting? ...

Issue with Angular 17 button click functionality not functioning as expected

Having trouble with a button that should trigger the function fun(). Here's the code snippet I'm using. In my TS file: fun(): void { this.test = 'You are my hero!'; alert('hello') } Here is the respective HTML: &l ...

React Sentry Error: Attempting to access properties of undefined object (reading 'componentStack')

Utilizing the ErrorBoundry component from Sentry in my react project has been a goal of mine. I aim to confine the errors reported to Sentry specifically for my React app, as it is deployed on multiple websites and I want to avoid picking up every JS error ...

How can you make an Angular directive activate only after the scope function in an ng-click handler has been executed?

Scenario I am relatively new to Angular and facing a specific challenge. The goal is to make a directive change the color and add an image to a button. However, I am struggling to get the first if condition to work in my Angular Directive. Issue The ob ...