Uncertainty surrounding the implementation of onclick function

Just starting out with JavaScript and hoping for some help understanding this.

1) Why isn't this code working as expected?

var allSpans = document.getElementsByTagName('span');
allSpans.onclick = function() {
 alert('hoo'); 
};

2) And what if I store all the innerHTML values from spans in an array and try this:

var allSpans = document.getElementsByTagName('span');
var arrayNumbers = [];

for (var i = 0; i < allSpans.length; i++) {
  var operator = allSpans[i].innerHTML; 
}
arrayNumbers.onclick = function() {
 alert('hoo'); 
};

Answer №1

  1. click is a characteristic of HTMLElementNode elements. The method querySelectorAll returns a collection called NodeList. Setting a property on a NodeList does not automatically apply it to each item in that collection.
  2. It's the same concept, just with an Array instead of a NodeList.

Answer №2

It is necessary to loop through the list that is returned

let spans = document.getElementsByTagName('span');

for ( let index = 0; index < spans.length; index += 1 ) {
    spans[index].onclick = function (event) {
         alert('hoo'); 
    };
}

Answer №3

In response to your initial inquiry, you must incorporate this code within each individual node rather than relying solely on the nodeList generated by calling document.getElementsByTagName. The solution you are seeking is as follows:

for(var i = 0; i < allSpans.length; i++){
  allSpans[i].onClick = function(){
    alert('hoo');
  };
}

A similar issue arises in the second query, where it seems that no elements are actually being added to the arrayNumbers array. Consequently, even if you were to iterate through it, the expected events wouldn't trigger upon clicking.

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

Struggling with displaying values from an array using getJSON

I've encountered an issue with displaying the results of a $.getJSON call. The code I have retrieves JSON data from a specific page. var loadItems = function() { if (hasNextPage === false) { return false } pageNum = pageNum + 1; var url = baseUr ...

Unable to modify the logo images in React

I'm struggling to figure out how to make my images (favorite.svg and favorite-white.sgv) change every time the button is clicked in React. I've tried various solutions but it's proving to be quite challenging. When the button is clicked, I ...

The share-modal.js file is throwing an error because it is unable to read properties of null, particularly the 'addEventListener' property, at

I encountered an error that I want to resolve, but it's proving to be quite challenging. Despite extensive searching on Google, I haven't found a solution yet. Uncaught TypeError: Cannot read properties of null (reading 'addEventListener&apo ...

Navigate to the appropriate Angular route using HTML5 mode in Rails

After removing the '#' symbol in angular by using html5Mode, everything seemed to work fine. However, upon refreshing the page, it started looking for the template in Rails instead of Angular, resulting in a "template not found" error. Angular R ...

Unable to retrieve the latest state changes in React

I'm encountering an issue where I am unable to access the updated state in a function. Here's what's happening: There is a getImages() function that gets called either when the component loads for the first time or when the user reaches the ...

Vue 3 project experiencing issue with Bootstrap 5 tabs failing to update upon tab click

Currently, I'm in the process of developing a vue3 application with bootstrap 5. As part of this project, I am implementing tabs. Although I can successfully click on the tabs, I have encountered an issue where the tab-content remains fixed on the ini ...

Working with AngularJS: How to sort ng-options when dealing with an object

Is there a way to sort the choices in a {select} like this? <select ng-options="value as name for (value,name) in vm.options" ng-model="vm.selected"> If the object vm.options is being used and sorting by values is desired, how can it be achieved? ...

What could be causing the fourth tab to not show any data while the first three tabs are functioning as expected?

I've encountered an issue with my HTML tabs. While I can easily switch between the first three tabs and view their content, tab 4 doesn't seem to display its associated data. It's puzzling why tab 4 is not working when the others are functio ...

Stopping React component click event from bubbling up to document

How do I prevent a click event in a React component from bubbling up to the document? There seems to be an issue that needs fixing! Let's see if we can resolve it on our own. I have a box component with a click event listener, and some link compone ...

Extracting information from a string with JSON in Javascript

Can you assist me? I have developed a web service that provides a clean string after clicking on the URL: { "PersonID": 125, "Title": "Security Officer", "Company": "TSA", "CellNum": "423-915-3224", "EmergencyPhone": "", "Email": " ...

Please add a new row following the date that falls on a Sunday using Google Apps Script

I have a dataset in my google sheets where one of the columns contains various dates. My objective is to add an empty row under every date that falls on a Sunday (regardless of the year). I am only concerned with identifying the day of the week. I have co ...

Error: Unable to iterate over the elements of `this.state` as it is

NEW UPDATE I encountered an issue with the response being an array, but it was actually coming from the backend (Express/Build folder) Revisiting an old issue that I faced some time ago. In my development environment, everything works fine. But once I d ...

When state is updated, the component is re-rendered multiple times

I am working on setting the state in componentDidMount lifecycle method to verify data from local storage. Depending on whether the data exists in local storage, I either redirect the user to the login page or keep them on the dashboard. Is there a way to ...

Interacting with Rails controllers through AJAX to trigger a JavaScript function

After exploring numerous stack overflow posts without finding a working solution, I decided to seek help for a well-documented use case. I have a button that should perform the following tasks: When clicked, call a custom controller method to update th ...

Transforming a base64 encoded string into a byte array

I have implemented a form where users can upload images to the page using an <input id = "fileLoader" type = "file" />. With JavaScript, I convert these uploaded images to base64 and send them to the server. On the server side, I need to decode this ...

Ways to activate onChange multiple times for a single item within material ui's autocomplete feature

I am utilizing the autocomplete component in the Material UI. Upon selecting an item, the onChange props are triggered and certain actions are performed. However, I am encountering an issue where I can select the same object multiple times without the on ...

Using Typescript to define unions with multiple callback types

While in the process of converting my code to TypeScript, I encountered a dilemma. I created a generic foreach function that can handle arrays and objects, with different types of callbacks for iteration. However, I'm unsure how to specify the type wh ...

What is the best way to dynamically add the 'required' attribute to an input field?

My responsibility was to dynamically add required fields to all elements on each state that the user selected as required. In my database, I have a table containing the input ID (each input has a unique ID) and a boolean field indicating whether or not a r ...

Determine the position and quantity of elements in jQuery by comparing their IDs with the current page or element

Looking to retrieve the n (zero based) position of an element by matching the page and element ID... Let's use an example (Assume the current page ID is 488); <ul id="work-grid"> <li id="item-486" class="work-item"><!--/content--& ...

In certain instances, a modal popup may intermittently fail to hide after the page has finished loading, an issue observed

Upon page load, an ajax modal pop-up is displayed and then hidden once the loading process is complete. This functionality is defined within the master page. The issue arises when certain button clicks fail to trigger the window.onload javascript event, as ...