Why is the size of my array shrinking with every iteration of the for-loop in JavaScript?

I am struggling to change the classname of three elements that share the same classname. Unfortunately, as I loop through my array, it seems to decrease in size with each iteration, preventing me from successfully changing all three elements. Any advice or guidance would be greatly appreciated as I am currently feeling quite lost.

javascript

 var i;

 for(i=0; i < toAssignArray.length; i++){
        console.log('size of aaray: '+ toAssignArray.length);
        console.log('id in array ['+ i +']: ' + toAssignArray[i].id);

        toAssignArray[i].className = 'toAssignOff';

        console.log('className of ['+i+']' + toAssignArray[i].className);

            }

HTML

 <div id="toAssign_thanhphan_618" class="toAssign" onclick="pcoment.assignThisAuthor('thanhphan', 'reply_618', '740')" style="display: inline;">Assign Comment</div>

 <div id="toAssign_jimmywhite_618" class="toAssign" onclick="pcoment.assignThisAuthor('jimmywhite', 'reply_618', '740')">Assign Comment</div>

         <div id="toAssign_anquoc_618" class="toAssign" onclick="pcoment.assignThisAuthor('anquoc', 'reply_618', '740')">Assign Comment</div>

console

[Log] size of aaray: 3 (pub_comments.js, line 604)
[Log] id in array [0]: toAssign_thanhphan_618 (pub_comments.js, line 606)
[Log] className of [0]toAssign (pub_comments.js, line 610)
[Log] size of aaray: 2 (pub_comments.js, line 604)
[Log] id in array [1]: toAssign_anquoc_618 (pub_comments.js, line 606)

Answer №1

An array is not what you have here, rather a NodeList. NodeList instances from various DOM APIs are considered to be live, meaning they change dynamically as the elements within them change. For instance, if you use .getElementsByClassName() and alter an element in the list so it no longer has the specified class name, it will immediately disappear from the list.

There are two methods to address this issue. Firstly, you can convert the NodeList into a traditional array. In modern JavaScript (ES2015), this process is quite simple:

var realArray = Array.of(nodeList);

In older ES5, the approach is slightly more complex but achieves the same result:

var realArray = Array.prototype.slice.call(nodeList, 0);

The second option involves iterating through the list differently. Instead of using a for loop with an index variable, one can utilize a while loop and only perform operations on the first element:

while (nodeList.length) {
  nodeList[0].className = ""; // or any necessary action
}

This method works best when consistently removing elements from the list. Otherwise, utilizing the "real array" method is recommended.

Another alternative would be to utilize a different API that does not return a live NodeList. The .querySelectorAll() function is a versatile API for selecting DOM nodes without returning a live list. Therefore, instead of employing .getElementsByClassName(), consider using:

var nodeList = document.querySelectorAll(".the-class-name");

Answer №2

To efficiently iterate through a dynamically changing node list, another common method is to reverse the loop direction:

  for(i=toAssignArray.length-1 ; i >=0; i--){...

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

Modification of text within a text field via a context menu Chrome Extension

Currently, I am embarking on my first endeavor to create a Chrome extension. My goal is to develop a feature where users can select text within a text field on a website using their mouse and have the ability to modify it by clicking on a context menu. Be ...

Error message: Next.js - Unable to access properties of an undefined object (user)

I am currently utilizing Next.js and Next-auth in my current project. Within this project, I am working on creating a Sidebar component that will display a list of items specific to each user. To achieve this, I am using the useSession hook to retrieve t ...

CodeIgniter - Utilizing quotes within a form

Consider a scenario where the database has a field named NAME which contains text with both single and double quotes: TEST1 "TEST2" 'TEST3' Now, if you want to edit this value using the following code in a form: <label for="name">Ful ...

The list item click event is not triggered when new list items are added

I've run into a bit of confusion with my code. Everything seems to be working perfectly fine until I introduce new items. Take a look at a sample of my items However, once I make changes to my list, the click function stops working. Check out a sa ...

Create a table that allows one column to have ample space, while ensuring that the other columns have uniform widths

This HTML/CSS creation features the following: https://i.stack.imgur.com/R8PRB.png However, the challenge lies in making the Very Good, Good, Fair, Poor, Very Poor columns equal in width while still allowing the "question" column to adjust its width acco ...

Creating protected routes in ReactJs using Typescript by utilizing a Higher Order Component (HOC) as

I'm struggling to create a basic HOC that can protect a component, ensuring that the user is logged in before rendering the component. Below is my attempt at building the protective HOC (not functional yet). export default function ProtectedRoute(Com ...

Adjust Mui Autocomplete value selection in real-time

I have implemented Mui AutoComplete as a select option in my Formik Form. <Autocomplete disablePortal options={vendors} getOptionLabel={(option) => option.vendor_company} onChange={(e, value) => {setFieldValue("vendor_id", value. ...

Image Placement Based on Coordinates in a Graphic Display

Placing dots on a map one by one using CSS positions stored in arrays. var postop =[{'top':'23'},{'top':'84'},{'top':'54'},{'top':'76'},{'top':'103'}]; var ...

Hide the dropdown menu when the user clicks anywhere else on the screen

I have a scenario with 2 dropdown buttons. When I click outside the dropdown or on it, it closes. However, if I click on the other dropdown button, it does not close and the other one opens. I want them to close when I click on the other button or anywhere ...

What is the reason in AngularJS for requiring directive attributes to be hyphen-separated while their scope variables are camelCased?

Here is an example in Html: <!-- Note 'display-when' is hyphenated --> <wait-cursor display-when="true"></wait-cursor> Then, when defining it in the directive: scope: { // Note 'displayWhen' is camelCased show: ...

How can the Material UI select component be customized to automatically scroll to the top when all items are selected?

After implementing the material ui select feature, I observed that when all items are selected, closed, and then reopened, the scroll position is automatically moved to the end. Is there a way to prevent this and keep it at the top? Current display: http ...

Ajax is coming back with a value that is not defined

Currently, I am working on a search function that is responsible for searching a name from the database. When the user clicks "add", the selected item should appear below the search field so that it can be saved in the database. However, I am encountering ...

Array Filtering with Redux

I have come across similar queries, but I am still unable to find a solution. While typing in the search box, the items on the screen get filtered accordingly. However, when I delete a character from the search box, it does not show the previous items. For ...

The behavior of Datatables varies depending on the screen resolution

In my data table, there are numerous entries with child tables on each row of the main table. I am currently in the process of incorporating this type of functionality into my table, with a few modifications to create a table within the child row. You can ...

How to locate a specific object by its ID within a JSON structure embedded in an HTML template

I am currently working on the page where I display posts. Within my controller, I have: export class PostsComponent implements OnInit { posts$: Object; users$: Object; constructor(private data: DataService) { } ngOnInit() { this.data.getPo ...

Issue with BackboneJS TypeError

I attempted to use the example below, but I encountered an error stating "TypeError: _.has is not a function". Example: I have experimented with different versions of jQuery and Backbone (uncompressed), yet the same error persists. Can anyone offer assis ...

The CSS transition feature does not seem to be functioning properly when it comes to displaying

In my Next.js application, I am using a card component with a "read more" link that should expand the card when clicked. To achieve this behavior, I integrated the "react-show-more" library from https://github.com/One-com/react-show-more. I tried to add ...

Angular 5 is throwing an error that says: "There is a TypeError and it cannot read the property 'nativeElement' because it

Being aware that I may not be the first to inquire about this issue, I find myself working on an Angular 5 application where I need to programmatically open an accordion. Everything seems to function as expected in stackblitz, but unfortunately, I am enco ...

Troubles with implementing child routes in Angular 6

I'm having trouble getting the routing and child routing to work in my simple navigation for an angular 6 app. I've configured everything correctly, but it just doesn't seem to be working. Here is the structure of my app: └───src ...

Dividing a pair of CSS stylesheets on a single HTML page

Currently, I am working on a HTML page that includes multiple javascripts and css files in the header section. <link href="@Url.Content("~/Content/css/main.css")" rel="stylesheet" type="text/css" /> In order to make the website mobile-friendly, I s ...