Generating a table in HTML using JavaScript

I encountered an unexpected issue...

// ticketList is the id of an html table
console.log("ticketList.rows.length before: " + ticketList.rows.length);
    for (i= 1; i < ticketList.rows.length; i++) {
        ticketList.rows[i].remove();
        console.log(`ticket ${i - 1} removed`);
    }

    // additional code that functions correctly

    console.log("ticketList.rows.length after: " + ticketList.rows.length);

Here is the output in the console:

ticketList.rows.length before: 13
ticket 0 removed
ticket 1 removed
ticket 2 removed
ticket 3 removed
ticket 4 removed
ticket 5 removed
ticketList.rows.length after: 19

The initial count of 13 seems correct. Why does it stop at 6 iterations instead of removing twelve elements as expected?

I attempted to manually set the end value in the for-loop and received this error:

Cannot read properties of undefined (reading 'remove')

Answer №1

When removing a row, it's important to consider the impact on your indexes. One simple solution is to loop backward through the rows.

for (let i = myList.rows.length - 1; i >= 0; i--) {
    myList.rows[i].remove();
    console.log(`Row ${i - 1} has been removed`);
}

If you only want to delete all rows except the first one, just adjust the condition to i > 0;

Check out this discussion on Removing elements effectively

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

Issue with Angular 6: date disappearing upon refreshing the page

While working with a textarea that allows users to submit comments, I encountered an issue. Whenever a comment is submitted, the date and time of submission are saved along with the comment in a JSON file. However, upon refreshing the page, the date inform ...

The routes may be the same in both React Router Dom v6, but each one leads to a different

I am struggling to set up different routes for navigation and I'm not sure how to do it. Here is what I have attempted so far: const router = createBrowserRouter( createRoutesFromElements( <> <Route path="/" element={<NavB ...

Issue with texture in three.js causing it to appear completely white

UPDATE: After taking advice from gaitat, I encountered a new issue: now the box is not visible at all. To illustrate this problem, I have created another question. I have a basic box geometry that I am attempting to apply a texture to. However, all I am g ...

Switching up specific information

After my return, I am faced with the challenge of changing the content of one select element based on the option chosen in another select element. You can find my JSFiddle here. My goal is to display only 28 days in the 'dia' select (days) when & ...

Angular examine phrases barring the inclusion of statuses within parentheses

I require some assistance. Essentially, there is a master list (arrList) and a selected list (selectedArr). I am comparing the 'id' and 'name' from the master list to those in the selected list, and then checking if they match to determ ...

Is there a sweet TypeScript class constructor that can take in its own instance as an argument?

I have a scenario where I need to read in instances of Todo from a CSV file. The issue is that Papaparse does not handle dynamic conversion on dates, so I'm currently dropping the object into its own constructor to do the conversion: class Todo { ...

Error encountered in attempting to create an embed using discord.js v14.7.1: TypeError - The value being extended, either undefined or null, is not a valid

The specific problem arises when defining the module export for the HelpCommand class: **module.exports = class HelpCommand extends Command {** The content of the help.js file, without URLs, is as follows: const fs = require('fs'); const { Comma ...

Stopping link navigation with JavaScript

Can someone help with my link element issue? <a href="javascript:;" onclick="check_show('http://www.test.com')">Test</a> <script> function check_show(link){ if($('#testelement).css('display') == 'block& ...

I am encountering an issue with React JavaScript Axios in my code. Can anyone provide guidance on how to optimize this data for

I'm having trouble with my code. I can't figure out how to effectively use Axios in this situation. import axios from "axios"; const options = { headers: { 'content-type': 'application/json', ContentType: ...

Run the code after a certain amount of time determined by the characters in JavaScript

list = ["Rashid", "Kalam", "NEO"] Rashid contains six characters, so it will be console.log after 6 seconds. Kalam has 5 characters, which means it should be logged on the fifth second, and so forth. ...

"Learn an effective method for presenting JSON variable data in a Bootstrap modal with a clean design using three distinct columns

I have successfully loaded JSON data into my HTML page using JQuery. By clicking a button, I can trigger a bootstrap modal that displays the content of the JSON variable. However, there is an issue with how the JSON data is displayed. I need the data to b ...

Guide to sending a post request in Node.js using Mongoose

I recently tried to follow a tutorial (https://medium.com/weekly-webtips/building-restful-apis-with-node-js-and-express-a9f648219f5b) from 2 years ago to build an API. However, I'm struggling to update the code to work with more recent changes in the ...

JavaScript recording speed

I am currently working on a project that involves video recording on my website. After creating a canvas and pushing the recorded frames to it, I have encountered an issue. The playback of the video is too fast - a 10-second video plays in around 2 second ...

I am looking to sort the salary information based on the radio button selected

When I click on the radio button in the code, I want to filter the data of the salary Array. The rendered data should be filtered according to the text on the radio button. The check box Array filtering is working fine, but after applying the same concept, ...

Verifying Dates with Bootstrap DatePicker

My bootstrap datepicker has a startDate value of '1/1/1990', but when a user manually enters a date like '1/1/201' (possibly a typo for '1/1/2014'), the date field becomes blank when they move to a different section. Is there ...

Rendering PDFs with JavaScript in Laravel 4

Is there a way to generate a PDF from an HTML view using Javascript APIs? Below is my code snippet in PHP Laravel 4: $con = Contrato::find($id); $html = (string) View::make('contratos.contratopdf')->with('con',$con)->ren ...

Utilize fullcalendar by setting the locale to a specific variable

Is there a way to dynamically pass the I18n.locale to fullcalendar, so that the calendar language can change based on the user's selected locale? This is my current JavaScript code: return $('#event_calendar').fullCalendar({ events: a ...

Utilize the toggle feature by retrieving the dynamic ID from ng-repeat within the scope

Hey there! I'm currently working on a UI that contains multiple links, and when clicked, each link should toggle to display different data. The challenge I'm facing is that the data is being generated dynamically using ng-repeat. How can I ensure ...

Detecting browser or tab closure in Node/Express Application: A comprehensive guide

As I'm developing a Node + Express MVC application, I am looking for a way to automatically shut down the Express server when the browser or tab is closed. While I know I can achieve this using a vanilla JS script with the 'beforeunload' eve ...

Unable to reach the form within the AngularJS controller

Having trouble accessing a form variable from my controller. When I try to access it using $scope.locationForm, it returns 'undefined'. However, when I use console.log($scope), I can see the locationForm in the console. Here is my HTML code: &l ...