When attempting to add event listeners in a forEach loop in Javascript, only the last entry seems to

I need help with a function that iterates through an Array and adds <h3> elements to a div. The function then attaches an event listener (an onclick) to the current <h3> element, but for some reason, only the last element processed by the function is triggering the onclick event.

var runstr = [];

//txt is derived from content in a tab-separated text file split by '\n'
txt.forEach(function (lcb) { //lcb iterates over each line of txt
    lcb = lcb.split("   ", 30); //split the line by tab
    //MainContent_Infralist is the div where the <h3> elements are listed and lcb[2] represents the title
    document.getElementById("MainContent_Infralist").innerHTML = 
        document.getElementById("MainContent_Infralist").innerHTML + 
        '<h3 class="Infraa" id="' + "Infralist_" + lcb[2] + '">' + lcb[2] + '</h3>';
    //I store the id in an array to retrieve the marker index later
    runstr.push("Infralist_" + lcb[2]);

    //I'm using openlayers here to trigger a mousedown on a marker when a list entry is clicked.
    //The issue arises where it only works for the last entry in my <h3> list...
    document.getElementById("Infralist_" + lcb[2]).onclick = function () {
        var theM = runstr.indexOf("Infralist_" + lcb[2]);
        markers.markers[theM].events.triggerEvent('mousedown');
    };
};

Answer №1

The issue lies in this particular section:

document.getElementById("MainContent_Infralist").innerHTML = 
     document.getElementById("MainContent_Infralist").innerHTML + 
     '<h3 class="Infraa" id="' + "Infralist_" + lcb[2] + '">' + lcb[2] + '</h3>';

Whenever you set the innerHTML, it essentially clears everything and then re-adds it back. Consequently, all event listeners get broken.

This explains why only the last one functions correctly - it's the only one where no more manipulation of innerHTML occurs after setting it.

To resolve this, construct your elements using document.createElement() and append them using element.appendChild().

You can try something like this:

var header = document.createElement('h3');
header.id ='Infralist_' + lcb[2];
header.className = 'Infraa';
header.textContent = lcb[2];

document.getElementById('MainContent_Infralist').appendChild(header);

header.onclick = function () {
  // Your function goes here
}

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

Placing the dropzone within a specific div container, rather than the entire

I am currently trying to implement dropzone into my form submission process by following this guide. However, the result is not what I expected. https://github.com/enyo/dropzone/wiki/Combine-normal-form-with-Dropzone After integrating dropzone, my catego ...

Learn how to use props in React with the PluralSight tutorial - don't forget to

While working through a React tutorial on PluralSight, I encountered an error that I'm not sure is my mistake or not. The tutorial directed me to the starting point at JS Complete using this URL: As I followed along, the tutorial led me to the follo ...

The Mongoose findByIdAndUpdate() method in NodeJS may sometimes result in a null return

Exploring the code snippet below in NodeJS, we focus on updating a document by its id: router.put('/:orderId', async(req, res) => { let update_orderId = req.params.orderId; let new_item = req.body.item; let new_item_desc = req ...

What is the best method for rotating segments in THREE.TubeGeometry?

I've successfully generated a flat tube structure using THREE.TubeGeometry with radiusSegments set to 2. However, once added to the scene, it appears perpendicular to the ground: https://i.sstatic.net/U3qTt.png Is there a way to rotate each segment ...

Receiving a JavaScript function's output with Python Selenium

Currently, I am in the process of scraping data from a specific webpage. The focus is on extracting the return string value from a Javascript function snippet. The target value to be extracted is indicated as "2227885" https://i.sstatic.net/5dLJ ...

jQuery Filter for Page Content - choose specific text within paragraphs and clickable links

I recently created a page search filter using Bootstrap 5, but it seems to only display text content and not any content enclosed within the a tags. You can check out the JS Fiddle link provided below for reference: https://jsfiddle.net/mfen723/rozy16pt/1 ...

What is the technique for integrating a required file into an Angular module using Browserify?

My Angular SPA build is set up to use NPM for calling the browserify script to bundle it. To execute the build process from the terminal, you can run npm run build:js, which triggers the following script in the package.json file: "build:js": "browserify - ...

Steps to update the package version in package.json file

If I remove a package from my project using the following command: npm uninstall react The entry for this package in the package.json file does not disappear. Then, when I install a different version of this package like so: npm install <a href="/cdn ...

Issue with Chrome extension's popup not displaying

I was developing a chrome extension, but I encountered an issue where the popup does not display when clicking on the icon. After researching online, I found suggestions to change page_action to browser_action. However, even after making this adjustment, ...

Aligning a div with absolute positioning vertically

There are two elements positioned side by side: an input field and a div. The div is absolutely positioned inside a relative element and placed to the right of the input. The input field has a fixed height, while the height of the div depends on its conte ...

The page's layout becomes disrupted when the back end is activated, requiring some time to realign all controls

I recently set up a website and I am facing an issue where certain pages shake uncontrollably when buttons are clicked. The problematic page can be found at the following link: Specifically, when trying to click on the "SEND OFFER" button, the entire pag ...

Unknown and void

undefined === null => false undefined == null => true I pondered the logic behind undefined == null and realized only one scenario: if(document.getElementById() == null) .... Are there any other reasons why (undefined === null) ...

Dividing an array of characters within an ng-repeat and assigning each character to its individual input tag

Hello, I'm currently learning Angular and I have a unique challenge. I want to take the names in a table and break each name into individual <input> tags, so that when a user clicks on a letter, only that letter is selected in the input tag. For ...

JavaScript Event Listener not Working Properly

I've been attempting to implement a feature on my website where the header hides when scrolling down and re-appears when scrolling up. However, I'm struggling to make use of the code snippet below to achieve this functionality. Despite my thoroug ...

Website experiencing issues with moderating Facebook comments

I recently added a Facebook comments box to my website in the footer. Although it is visible, I am unable to moderate it. Furthermore, the comments are not showing up in the comments queue panel at https://developers.facebook.com/tools/comments. I am us ...

The rule result is invalid due to the occurrence of the Function()

As I proceed with the upgrade from angular 6 to angular 7, I am diligently following the guidelines provided on the official Angular website. Upon executing the command to update angular/cli and core for version 7: $ ng update @angular/cli@v7 @angular/c ...

The jQuery UI Modal Dialog ensures that no postback will occur

Is there a way to trigger a postback in ASP.NET when using a submit button within a jQuery UI dialog? I am currently utilizing the UI dialog modal to update data in a gridview control, similar to how it was done with the Ajax control toolkit's modal. ...

Save a specific collection of divs from a webpage as a PDF or Word document

Could the following scenario be achievable? Imagine a webpage containing a series of div elements with unique IDs or classes. Inside each div, there is a title (possibly an h1 tag) and some additional content. Is it possible to create a selection list of t ...

Remove Angular.js entirely from your system

Is it okay to remove all Angular files and directories without causing any issues? I've searched for information on uninstalling Angular but have come up empty-handed. ...

Sending information from Node.js to the backend using AJAX involves a seamless communication process

I'm relatively new to working with AJAX, so please excuse any misunderstandings I may have. I am still in the process of learning. My current task is quite simple. I have a backend file named server.js, an index.html file, and a script.js file. It&ap ...