Issue with event delegation when using if-else conditions is not being resolved

I have set up an event listener on an HTML container, and when the user clicks on the play again button, the code inside the 'if' statement should be executed. However, nothing happens when clicking on the play again button and no logs are output to the console. I've tried different methods such as checking if the element has a particular class name.

Here is the relevant snippet of HTML:

<div class="play-again-btn">
 <input type="button" class="play-btn" value="PLAY AGAIN">
</div>

This is where the event listener is attached to the container:

document.querySelector(DOMstrings.endContainer).addEventListener("click", playerCtrl.playAgain);

Below is the playAgain method:

playAgain: (event) => {
            let finishedPlayer, parentEl;

            console.log(event.target);

            //1. Perform actions only if correct button is clicked
            if (event.target.nodeName == "input") {

                //2. Remove existing character from finish line
                finishedPlayer = document.querySelector(DOMstrings.finishBox);
                finishedPlayer.removeChild(finishedPlayer.childNodes[0]);

                //3. Display character select pop up
                document.querySelector(DOMstrings.usersInput).style.visibility = "unset";

                //4. Remove leaderboard pop up 
                parentEl = document.querySelector(DOMstrings.endContainer);
                parentEl.removeChild(parentEl.childNodes[1]);
            }

          },

Answer №1

The property Node#nodeName stores the node type (such as Text, Element, Comment, etc.) and not the tag name of the HTML element it represents.

Therefore, Node#nodeName will never be equal to "input," causing your code not to execute as expected.

To check for the tag name, you should use Element#tagName instead:

if (event.target.tagName == "input") {

Furthermore, rather than checking explicitly for "input," it may be more efficient to determine if the clicked element is specifically your button. In this case, performing an equality check with the selected button would be preferable:

if (event.target === document.querySelector(selectorOfButton)) {

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

Contrast the table column to a JSON object and modify a different column in an HTML file

This Dashboard is my first venture into using HTML and Javascript to create an interactive display. The table within this Dashboard showcases server names, descriptions, and time-related columns for uptime, warning, and critical statuses. To generate an A ...

Dealing with null route parameters for Express applications

I am facing a challenge in handling an empty route parameter when a path is not specified. My intention is to return a new date if the route parameter is empty. However, the server's response so far is: Cannot GET /api/timestamp/ app.get("/api/timest ...

Creating a mongoDB query that matches elements in an array of subdocuments with elements in a Typescript Array

In my database, I have stored various Events using mongoDB. Each event comes with multiple fields, including an array of genres, which consists of subdocuments like {genre and subGenre}. For instance, an event could be classified as {genre: "music", subGe ...

How to play audio with a source path that includes the special character "%" in JavaScript

Having an issue with playing an audio file that has '%' in its name. I've tried using the tag <audio src="test%320.mp3" controls></audio>, but it seems like the file is not being found when I try to play it. Can anyone ...

What steps can I take to generate 12 random div elements using jQuery out of a pool of 30?

Currently, all the words are displaying, but I would like the script to randomly select 12 out of the 30 words var randomdivs = $("wordstyle").get().sort(function(){ return Math.round(Math.random())-0.5; }).slice(0,12) $(randomdivs).show(); The follo ...

Incorporating Tinymce into a dialog with Vuejs & Vuetify may necessitate a refresh

I have implemented tinymce as a component for creating and editing articles In addition, I am using vuetify along with the v-dialog component, and all my form fields are within this modal However, each time I change the instance of the tinymce component, ...

What is the most effective way to extract content values from different divs for calculation using jQuery?

I am working on creating a function that retrieves the content values from the <div class="rowtabela"> div and reads the nodes of <div class="item v_...">. Check out my code below: <div class="adicionados" id=& ...

What is the best approach for dynamically appending new elements to a JSON array using PHP?

I am facing an issue with the JSON below: [{"username":"User1","password":"Password"}, {"username":"User5","password":"passWord"},] The above JSON is generated using the PHP code snippet mentioned below: <?php $username = $_POST["username"]; ?>&l ...

Setting global variable values when a button is clicked in Javascript

My query involves JavaScript. I have an HTML template with a button (b1) that, when clicked, assigns an array to a variable called tempdata. The issue arises when trying to display this tempdata array using alert() outside the onclick function; nothing hap ...

Combining Rails 4 with coffeescript while encountering an issue with the jQuery sortable detatch functionality

Currently, I am using Ruby on Rails 4 along with the jquery-ui-rails gem. Within my application, there are certain lists that have a sortable jQuery function implemented. $ -> $('#projects').sortable handle: '.handle' ...

I encountered an issue where my button's onClick function was not functioning properly with the clickable component

Here is my display I have a component(Product) that can be clicked. One of its children is also a button. However, when I click it, the Product's function runs. How can I make sure my button executes separately? <ProductForm> ...

Single input results in array output

I have a pair of items in this array list. $.each(data.recalls,function(i) { var recall = data.recalls[i].nnaId; var description = data.recalls[i].remedyDescription; console.log(recall); console.log(description); $('textarea[name= ...

Looking for assistance in showcasing information retrieved from an external API

I've been working with an API and managed to fetch some data successfully. However, I'm having trouble displaying the data properly in my project. Can anyone provide assistance? Below is a screenshot of the fetched data from the console along wit ...

Navigating through div elements using arrow keys in Vue

Trying to navigate through div elements using arrow keys is proving to be a challenge for me. I have successfully achieved it in JavaScript, but I am facing difficulties doing it the "vue way". Although there should be no differences, it simply does not wo ...

Create PDFs using PhantomJS when the HTML content is fully loaded and ready

I am a newcomer to utilizing phantomjs and encountering difficulties in rendering my website as a PDF file. Although I can successfully render a simple version of the page, issues arise when multiple images and web fonts are involved, causing the DOM not t ...

Tips for transforming JSO into JSON data format

Here is an example: var info = [{"name":"john","age":"30"},{"name":"smith","age":"28"}] I am looking to convert the above json object to a format like this result: [{name:"john",age:30},{name:"smith",age:28}] Any suggestions on how to achieve this? ...

Ensure that newly added elements are aligned with the settings of the slide's

I've encountered an issue with my jQuery slider that affects a div's CSS on slide. Everything works as expected, except when I add a new div, the settings from the slider aren't applied to the new div until the slider is moved again. HTML ...

What is the best way to determine the width of a div within a window that has been rendered using React?

I'm working on a task where I need to determine the size of a div (with CSS width set to 100%) and adjust the zoom factor of a component based on this size. The challenge arises during the initial run of the application when the div has not yet been c ...

Validate if the JSON data array contains any elements

I'm currently working with an ajax code and I need to determine whether the JSON data contains an array or not. However, despite my attempts, I am still receiving incorrect output. $.ajax({ url: url, type: 'POST', da ...

Problem with single-table layout in DynamoDB and constraints on query parameters

I'm trying to limit the elements I fetch in each query, but encountered an issue: Using the single-table design in DynamoDB, I am only getting four items. https://i.sstatic.net/N4wVS.png If I check the first 10 elements in DynamoDB, I always get a ...