Error: The method ele.addEventListener is not valid

Can someone please help me identify the issue in my code? I've included both HTML and JavaScript below. The code runs without any errors in Visual Studio Code, but when I try to use it on an online site, I get the following error message: "Uncaught TypeError: ele.addEventListener is not a function".

**<input type="text" name="" id="mon" class="key" placeholder="Monday">
<input type="text" name="" id="tues" class="key" placeholder="Tuesday">
<script>
var ele = document.querySelectorAll("#mon, #tues");

ele.addEventListener('keypress', demo);

function demo(){
alert();
}
</script>**

Answer №1

Given that ele represents the NodeList array, an addEventListener has been linked to each individual Node.

<input type="text" name="" id="mon" class="key" placeholder="Monday">
<input type="text" name="" id="tues" class="key" placeholder="Tuesday">
<script>
var ele = document.querySelectorAll("#mon, #tues");
 for (let i = 0; i < ele.length; i++) {
     ele[i].addEventListener("click", demo);
 }


function demo(){
alert();
}
</script>

Answer №2

document.querySelectorAll gives back a list of elements instead of a single one. This means that ele is actually an array, making it impossible to attach an eventListener directly to an array.

If you want to apply the same eventListener to all elements in the el array, you'll need to loop through each element and add the listener individually, like so:

for (var el of ele) {
  el.addEventListener('keypress', function() {
    alert();
  });
}

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

Utilizing SVG icons with AngularJS for optimal compatibility in Firefox

When integrating SVG icons with AngularJS and enabling html5Mode, it is essential to set the basePath in the html document's head. <base href="/"> To utilize SVG icons, all symbols need to be loaded into the index.html page like so: <?xml ...

Multiplying array elements within the Vuex state with the assistance of Socket.io

I have developed an application using Vue and Vuex that connects to a Node/Express backend with Socket.IO to instantly push data from the server to the client when necessary. The data sent to the clients is in the form of objects, which are then stored in ...

Count the occurrences of values in a JSON object using JavaScript

I'm dealing with a JSON array in vanilla JavaScript (no JQuery) and I've hit a roadblock. My task is to identify each unique value for 'Service' and calculate the frequency of each value. For example, if the value 100 appears 3 times ...

Does Mongoose use asynchronous saving?

Just starting out with mongoose and node. I'm trying to determine if the mongoose document.save method is asynchronous. Based on my observations, it seems to work even when not connected. Is there any way to know for sure when the document has been s ...

Zurb Foundation's sections have a strange issue where navigating between them introduces unexpected whitespace

I'm feeling frustrated as I try to work with Zurb Foundation sections. I've updated to the latest version 4.3.1. Following the documentation provided here: but encountering strange behavior while navigating through results. Refer to the screen ...

A guide on tallying blog categories using Django and showcasing them on a template

I'm currently learning how to build a blog using Django, and I have functions for post_list, category_detail, and post detail. However, I'm facing an issue with the post_list function that renders a blog.html page. I want to display the blog cate ...

Handling node_redis callbacks in Node.js

Delving into node.js has been quite the adventure for me, though I admit that I may be missing a few key points along the way. My main goal is to query an hmap containing a list of rooms and then iterate through each room to gather more details such as the ...

Exploring Ways to Modify a .txt File with Javascript or jQuery Forms

Looking for a way to access a .txt file offline in the browser and display its data in different form fields for each line. Any tutorials available for this? ...

Pressing the enter key within Material UI Autocomplete will allow you to quickly create new

Wouldn't it be great if Autocomplete in material ui could do this: wertarbyte Imagine being able to insert text (string) without the need for a list of elements to select from. This means that the noOptions message shouldn't appear, and instead ...

The Bootstrap modal is not properly clearing all attribute properties when it is hidden

Alrighty, so I've got this modal set up: <div id="modal-container" class="modal fade" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> <div class="modal-content center-block" style="displ ...

I am trying to launch an Android application on a device using Appium and Desired capabilities, but I am facing difficulty in navigating to elements that are not currently visible

When using Appium and Desired Capability to launch an Android application on a device, I encountered difficulty navigating to elements that are not in the screen view of the same page. Attempting to use JavaScriptExecutor proved to be incompatible with A ...

Certain characteristics remain constant while others experience variations

I have a code that successfully changes the header opacity when scrolling down, but now I want it to change the background color instead. Strangely, the code does not seem to affect this attribute, although it works fine for other attributes like opacity a ...

What is causing my console to be spammed by Web3 .GetReserves()?

My code is successfully retrieving the data, but I am encountering an issue where my request for token reserves ends up spamming the server with repeated requests. This causes me to temporarily lose access to data retrieval (I hope I'm not the only on ...

Choose various cells on the grid of a canvas by dragging the mouse

I am trying to incorporate a feature where users can select multiple cells on the grid chart by dragging. However, I am facing an issue with the functionality - instead of forming a square while moving the mouse, it currently draws a square when I drag and ...

Checking with jQuery Validate: displaying an error message if input matches a certain value

I spent 6 hours trying to figure out a solution to my issue. Currently, I am utilizing the jQuery Validation plugin. In my form, there is a password input field. When an AJAX request detects an incorrect password, another input field is set to a value of ...

Keep the sidebar in place as soon as one of its child elements reaches the top, ensuring that the child element remains on top of it with an automatically

Having an issue making my sidebar stick at the correct height and produce the desired effect. Here's my code: https://jsfiddle.net/oavgLrf9/ The problem arises when I want my sidebar to add a fixed class when the second module reaches the top. Both ...

the else/if statement executes only on the first run

In my current code, when the user inputs a color that matches any of the colors in the array, it will add that color class to the main div. The issue I'm facing is that my else-if statements only run once. If you input the same color again, it won&ap ...

Click on a button to display the corresponding DIV while hiding the rest, all achieved with the power of Vue

I'm seeking guidance as a newcomer to Vue, so please bear with me if my question appears simplistic. My scenario involves a set of buttons and corresponding div elements. The goal is to show a specific div when its associated button is clicked, while ...

Utilizing Metalness with the MTLLoader in three.js

Lately, I've been utilizing MTLLoader to load my obj meshes in Threejs. Although it does the job by loading the correct textures, the material appears too dull for my liking. My expectation: https://i.sstatic.net/Z2T9d.png What I am currently seei ...

Is there a way to reverse the process of Date.parse?

After converting a date to a number with the following code: Date.parse(doc.createdAt); I receive this result: 1576699528000 It seems like the number becomes a string when passed from the server to the front end and back to the server. How can I conver ...