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

What can you do with jQuery and an array or JSON data

Imagine having the following array: [{k:2, v:"Stack"}, {k:5, v:"Over"}, , {k:9, v:"flow"}] Is there a way to select elements based on certain criteria without using a traditional for/foreach loop? For example, can I select all keys with values less than ...

What is the process for sending a message from the internet to a mobile device?

We are currently in the process of developing a website that sends SMS alerts to users for specific services, however I am struggling to set up a script that can perform this function. If anyone has any suggestions or recommendations for a solution, pleas ...

The given 'FC<ComponentType>' type argument cannot be assigned to the 'ForwardRefRenderFunction<unknown, ComponentType>' parameter type

Currently, I am using react in conjunction with typescript. Within my project, there are two components - one serving as the child and the other as the parent. I am passing a ref to my child component, and within that same child component, I am binding my ...

Discover the power of utilizing JavaScript to sort through table rows by filtering them based on the selections of multiple checkbox

How can I create interdependent logic for checkbox sections in a form to filter based on all selections? I am looking for help with my code snippet that showcases checkboxes controlling the visibility of table rows: $(document).ready(function() { $(" ...

managing nested JSON arrays in JavaScript

I have a straightforward task with handling a simple array that is divided into two parts: a group of vid_ids and a single element named page. Initially, I was iterating through the vid_id array using a for loop. However, upon adding the page element, I en ...

Creating a modal form with jQuery in ASP.NET

I'm fairly new to ASP.NET development and have been able to work on simple tasks so far. However, I now have a more complex requirement that I'm struggling with. My goal is to create a modal form that pops up when a button is clicked in order to ...

The conversion of a newline in an Angular page is done using &lt;br/&gt tag

Here is a function I have: setLocalVariableOnAccepted(ogp, hb, responseJson) { if (responseJson.ofgp === undefined) { this.ogpStatus = 'orange'; this.ogpStatusMsg = responseJson.ofgp + ', <br/> No change. Previous va ...

Enable row selection in UI-Grid by clicking on a checkbox with AngularJS

I am a newcomer to angular js and I am looking to have the checkbox automatically selected when clicking on a row to edit that specific cell. I have implemented a cell template to display the checkbox in the UI-grid, but now, when I select a row, the row i ...

Get the JS file by tapping the download button, and access the

In creating the web page, I utilize a modular approach. Leveraging node js and the node-static server are essential components of this process. One specific requirement I have is implementing file downloads from a computer to a device using a button trigg ...

How to ensure your content is always visible on Mobile Safari iOS 8 by making sure it stays

Although minimal-ui is no longer supported on iOS8, I've encountered an issue with some fixed content at the bottom of a webpage. The page height is set to 100vh to cover the entire viewport, but some of the content at the bottom is extending below t ...

Updating an SVG after dynamically adding a group with javascript: a step-by-step guide

Currently, I am working on a circuit builder project using SVG for the components. In my HTML structure, I have an empty SVG tag that is scaled to full width and height. When I drag components from the toolbar into the canvas (screen), my JavaScript functi ...

What alternatives are there to angular scope functions?

I find angular scope functions challenging to work with due to their lack of a clear contract. They extract parameters from the scope and store results back into the scope, rather than explicitly defining function parameters and returning a result. Conside ...

Error message thrown by node express.js indicating that response headers cannot be reset once they have been sent

As a newcomer to both node and express, I may be making a silly mistake. If you want to see the complete source code, please visit: https://github.com/wa1gon/aclogGate/tree/master/server logRouter.get("/loggate/v1/listall", function(req, res) { let ...

Incorporating Stripe into your Next.js 13 application: A step-by-step guide

Struggling to incorporate Stripe into my Next.js 13 app for a pre-built checkout form. So far, all attempts have fallen short. Seeking assistance from anyone who has conquered this integration successfully. Any tips or guidance would be highly valued. Pl ...

Sorting `divs` based on the number of user clicks in JavaScript: A simple guide

I've implemented a script that tracks the number of clicks on each link and arranges them based on this count... Currently, everything is functioning correctly except when the <a> tags are nested inside a div. In such cases, the script ignores ...

How to process and handle a JSON response containing multiple objects using JavaScript

I received a JSON response that looks something like this. { returnCode: 'Success', info: null, result: { payload: '{ "BatchNo":"143123", "Supplier":"Automotive", "ItemNumber":"AP123", ...

The map markers are nowhere to be found on the map when using Internet Explorer

Take a look at this code I wrote... var styles = [ { "featureType": "landscape", "stylers": [ {"weight": 0.1}, {"color": "#E7EDEF"} ] }, ... { "featureType": "poi.park", "elementType": "labels", "stylers": [ ...

Asynchronous Return in NodeJS Class Methods

Currently, I am in the process of developing a JavaScript class that includes a login method. Here is an overview of my code: const EventEmitter = require('events'); const util = require('util'); const Settings = require('./config ...

Experiencing difficulties with mocha and expect while using Node.js for error handling

I'm in the process of developing a straightforward login module for Node. I've decided to take a Test-Driven Development (TDD) approach, but since I'm new to it, any suggestions or recommended resources would be greatly appreciated. My issu ...

React does not recognize data.map as a function

Currently, I am facing an issue with a simple map function in React that is supposed to create a set amount of times. {times.map((time) => ( <Pill value={time} handleTimes={handleTimes} key={time} /> ))} The error being thrown i ...