A single iteration is all that a for loop in Javascript will complete

I've been working on some code and I'm a bit puzzled by why the for loop seems to only run once, both inner and outer. Even though nodeList.length and innerNodeList.length are showing the correct values when I use alert messages. It's strange that neither i nor j increment past 0. Can you help me figure out what might be wrong with the code?

function getCategoryElements() {
var newCategoryDiv = document.getElementById("category");
var nodeList = newCategoryDiv.childNodes;

for (var i = 0; i < nodeList.length; ++i) {
    var innerNodeList = nodeList[i].childNodes;
    alert("innerNodeList Length" + innerNodeList.length.toString());

    for (var j = 0; j < innerNodeList.length; ++j) {
        if (innerNodeList[j].nodeName == "SELECT") {
            alert("inside select Node value " + innerNodeList[j].nodeValue.toString());
            document.getElementById("newCategories").value = 
                document.getElementById("newCategories").value + '<%=delimiter%>' + innerNodeList[j].nodeValue;
        } else if (innerNodeList[j].nodeName == "TEXTAREA") {
            document.getElementById("newCategoriesData").value =
                document.getElementById("newCategoriesData").value + '<%=delimiter%>' + innerNodeList[j].nodeValue;
        }
    }
  }
}

Answer №1

let categoryDiv, nodeListItems, innerNodesList, singleNode, index, subIndex;

categoryDiv = document.getElementById("category");
nodeListItems = categoryDiv.childNodes;

for (index = 0; index < nodeListItems.length; ++index) {
    innerNodesList = nodeListItems[index].childNodes;
    alert("Length of Inner Nodes List: " + innerNodesList.length.toString());

    for (subIndex = 0; subIndex < innerNodesList.length; ++subIndex) {
        singleNode = innerNodesList[subIndex];
        if (singleNode.nodeName === "SELECT") {
            alert("Value inside Select Node: " + singleNode.nodeValue.toString());
            document.getElementById("newCategories").value += '<%=delimiter%>' + singleNode.nodeValue;
        } else if (singleNode.nodeName === "TEXTAREA") {
            document.getElementById("newCategoriesData").value += '<%=delimiter%>' + singleNode.nodeValue;
        }
        // Can we get this to work?
        alert('Will this alert show up?'); 
    }
}

I've taken the initiative to optimize and streamline your code for better readability. Remember that in JavaScript, all variables have function scope.

As your code seems correct syntactically, it's possible that an error may be occurring after the final alert call. To investigate, consider adding another alert at the end of the inner loop. If it doesn't execute, you'll know where to focus your debugging efforts.

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

Disrupting methods on a dependency within QUnit can cause tests against that dependency to fail

Currently, in my Google Apps Script project, I am unit-testing an application using QUnit for test-driven development purposes. Code Under Test The function I am currently focusing on testing and developing is the creation of a Sheet from a long string o ...

Tips for enhancing the vertical-exclusive Masonry grid formula?

I have successfully implemented the core algorithm for the Vertical-only Masonry grid. This algorithm takes an array of items data and creates a required number of columns, where items are sorted to efficiently utilize the available space. Each column shou ...

Confirming whether the digit entered in jQuery is a number

My website has a user input field where numbers are expected to be entered. I wanted to find a convenient way to validate the input using jQuery. After some research, I discovered jQuery's built-in function called isDigit. This handy function allows ...

Ray casting in Three.js used to target specific points

I am currently working on creating a network visualization using Three.js, and I have encountered an issue with my ray casting implementation. It seems that the points being identified by the ray caster are not the correct ones (Here's the full exampl ...

Utilizing Three.js to showcase large 3D images from a JSON file

I am in need of showcasing 3D images. I have a .obj file that is 80 MB in size which I converted to a json file size of nearly 75 MB. While using three js, I managed to display a rotating 3D image, but the main issue is the loading speed, which currently t ...

AngularJS is not immediately responsive to changes in $window.document.visibilityState

I am currently working with AngularJs version 1.4 and I need to be able to detect when a user is not on the tab of my app and when they return. To achieve this, I attempted using $watch in the following way: $rootScope.$watch(angular.bind($window, functio ...

Filter out discord messages for deletion

A script was created to automatically delete messages from offline users during chat sessions on Discord. If an offline user attempted to chat, their message would be deleted, and a notification would be sent to the console indicating that offline chat was ...

Creating an HTML table with two arrays displayed and a delete button for confirming deletion

I have created a function to populate two arrays with movie information and display it in a table on the screen. However, I am struggling to make the delete button appear and to separate the titles and directors into different columns. How can I achieve ...

The TypeORM connection named "default" could not be located during the creation of the connection in a Jest globalSetup environment

I've encountered a similar issue as the one discussed in #5164 and also in this thread. Here is a sample of working test code: // AccountResolver.test.ts describe('Account entity', () => { it('add account', async () => { ...

The onmouseout event seems to be malfunctioning, whereas onmouseover is functioning properly

Forgive me if you're viewing this post twice, I believe I could have clarified things better. Essentially, I am designing a page that contains numerous elements. When the mouse hovers over an element, a "status" box should overlay on top of it. This ...

Conceal one object when the other is revealed?

Is there a way to hide the element with the class .close-button while showing another element with the ID #loading-animation? Can jQuery conditionals help achieve this? For example: if ($('#loading-animation').is(':visible')) { $ ...

What is the method to initialize a Stripe promise without using a React component?

I have encountered an issue while implementing a Stripe promise in my React app. The documentation suggests loading the promise outside of the component to prevent unnecessary recreations of the `Stripe` object: import {Elements} from '@stripe/react-s ...

Issue with Mongoose's deep population feature not functioning as expected

I'm currently working on a web application that requires the use of mongoose-deep-populate. I've already installed it using npm, but unfortunately, I keep encountering the following error: Error: Plugin was not installed at Query.deepPopulate (/ ...

Which is the better approach for performance: querying on parent selectors or appending selectors to all children?

I currently have 2 mirror sections within my DOM, one for delivery and another for pickup. Both of these sections contain identical content structures. Here's an example: <div class="main-section"> <div class="description-content"> ...

Instant data entry upon clicking

In an attempt to automate input based on image pairs, I encountered a challenge. On one side, there are two images that need to be matched with input fields, and on the other side, there are corresponding letters for each image to fill in the inputs upon c ...

How do I overwrite this calculation using JQuery?

I have a website: link There are two pages on my site that have the same div elements... I want one page to perform a certain calculation on the divs, and another page to perform a different calculation... New JavaScript Code: jQuery(document).ready(fu ...

"Using version 4.2.6 of NodeJS, create a constructor that takes a literal object as a

Currently, I am using NodeJS v4.2.6 which unfortunately has an issue with Block-Scoped declarations not being fully supported yet. Due to certain constraints, I am restricted to this version and have resorted to including the "use strict"; line to prevent ...

What is the best way to assign a value to this.var within a function nested in the same class in JavaScript?

Can anyone help me figure out why I can't set the this.session variable from within the last this.rpc using this.setSession()? I am new to JavaScript classes and transitioning from PHP, so I'm struggling with this concept. function glpirpc(host, ...

In Backbone.js, specialized events are dispatched to cater to unique needs

In search of a sleek JavaScript animation to have some balls gracefully moving within a canvas, I aim to implement collision detection using custom events managed through Backbone.js rather than resorting to an intricate nested loop to monitor interactions ...

Javascript is throwing a reference error because it can't find a definition for StringBuilder

I have a JavaScript function that utilizes a string builder function. It works smoothly in most major browsers like IE8+, Chrome, and Firefox but occasionally I encounter an error stating "stringbuilder is not defined". This issue seems to only affect cert ...