Check if there are any child nodes before executing the RemoveChild JavaScript function to avoid any errors

function delete(){
let k = document.getElementsByClassName('row');
for(let i=0; i<k.length; i++)
{
    if(k[i].hasChildNodes()){
        k[i].removeChild(k[i].childNodes[2]);
    } 
}
}
<div id="table">
    <div class="row">
        <div class="column">1.1</div>
        <div class="column">1.2</div>
        <div class="column">1.3</div>
        <div class="column">1.4</div>
        <div class="column">1.5</div>
    </div>
    <div class="row">
        <div class="column">2.1</div>
        <div class="column">2.2</div>
        <div class="column">2.3</div>
        <div class="column">2.4</div>
        <div class="column">2.5</div>
    </div>
    <div class="row">
        <div class="column">3.1</div>
        <div class="column">3.2</div>
        <div class="column">3.3</div>
        <div class="column">3.4</div>
        <div class="column">3.5</div>
    </div>
    <div class="row">
        <div class="column">4.1</div>
        <div class="column">4.2</div>
        <div class="column">4.3</div>
        <div class="column">4.4</div>
        <div class="column">4.5</div>
    </div>
    <div class="row">
        <div class="column">5.1</div>
        <div class="column">5.2</div>
        <div class="column">5.3</div>
        <div class="column">5.4</div>
        <div class="column">5.5</div>
    </div>

</div>

<div id="button">
    <input type="button" onclick="delete()" value="delete">
</div>

Trying to remove every second column using the method removeChild() in JavaScript, facing an error when there are no remaining children to delete. The console displays "

Uncaught TypeError: Failed to execute 'removeChild' on 'Node': parameter 1 is not of type 'Node'"
when all columns are already removed.

Question: How to handle this error condition? Can I use if(!k[i].hasChildNodes()) or another method to check if there are no more children before deleting? How would I go about implementing a condition to handle this situation?

Answer №1

If you're looking to simplify the process of removing specific elements, consider using a direct selector along with the :nth-child(2) method, followed by the .remove() function to delete all elements that match the selector:

function deleteRow() {
  document.querySelectorAll('.column:nth-child(2)').forEach((child) => {
    child.remove();
  });
}
<div id="table">
  <div class="row">
    <div class="column">1.1</div>
    <div class="column">1.2</div>
    <div class="column">1.3</div>
    <div class="column">1.4</div>
    <div class="column">1.5</div>
  </div>
  <div class="row">
    <div class="column">2.1</div>
    <div class="column">2.2</div>
    <div class="column">2.3</div>
    <div class="column">2.4</div>
    <div class="column">2.5</div>
  </div>
  <div class="row">
    <div class="column">3.1</div>
    <div class="column">3.2</div>
    <div class="column">3.3</div>
    <div class="column">3.4</div>
    <div class="column">3.5</div>
  </div>
  <div class="row">
    <div class="column">4.1</div>
    <div class="column">4.2</div>
    <div class="column">4.3</div>
    <div class="column">4.4</div>
    <div class="column">4.5</div>
  </div>
  <div class="row">
    <div class="column">5.1</div>
    <div class="column">5.2</div>
    <div class="column">5.3</div>
    <div class="column">5.4</div>
    <div class="column">5.5</div>
  </div>

</div>

<div id="button">
  <input type="button" onclick="deleteRow()" value="delete">
</div>

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

Is there a way to properly structure a JSON file for easy reading on localhost

I am having trouble with the formatting of my .json file while using backbone.js. I can't seem to pass in the url correctly. PlayersCollection = Backbone.Collection.extend({ model: Player, url: 'http://localhost/STEPS/data/players.js ...

Displaying a DIV inside an embedded DIV when selecting an option in HTML by utilizing JavaScript

My goal is to create a page where users initiate a questionnaire by clicking START in a web form - this action will open the DIV for the first question. As users answer each question (with yes/no choices), it will either display a specific DIV related to ...

Change the ng-model of the initial controller when a button is clicked in a separate controller

I am working on an AngularJS application that has two controllers. I am facing an issue where I need to update the ng-model of an input field in the first controller by clicking a button in the second controller. Accessing the $scope of the first controlle ...

What exactly is the purpose of editing a host file?

After reviewing this repository, an automatic message pops up: Don't forget to modify your host file 127.0.0.1 * http://localhost:3001 What exactly does that entail? ...

Substituting ng-init with scope variables results in failure

Why is nothing rendering when I try to use scope instead of ng-init in my AngularJS code below? <!doctype html> <html ng-app="myApp" ng-controller="myCtrl"> <head> <title>Bookshop - Your Online Bookshop</title&g ...

Extracting values from PHP using AJAX

Whenever a user clicks on the download button, a zip file is successfully created on the server with the necessary files. However, instead of getting an alert with the location of the zip variable ($zip) from PHP as expected, it shows [object Object]. The ...

Sending a notification alert directly to the client's web browser

My goal is to develop an application that allows Super users to notify other users by providing access to content, such as a PDF file, when they click on a link. For example, in the scenario where a teacher wants to share a PDF with students, this applica ...

Struggling to update the position of an array and dynamically show its contents using Angular

I am working with an Array of Objects, each containing an Array of strings. Utilizing ng-repeat to display all the strings, I have a button to switch to the next set of strings by changing the selected object in the outermost array. Below is the code snipp ...

Symfony is unable to access uploaded files from an AngularJS interface

For the past 3 days, I've been grappling with uploading files via AJAX to my Symfony2 application using AngularJS. I'm utilizing my Symfony app as an API to deliver data to my Angular front end. While I can successfully post text and other data, ...

Has Next.js incorporated a maximum cache size feature along with an invalidation algorithm like LRU?

Currently, I have a Next.js site that utilizes getServerSideProps for data fetching. However, I am interested in switching to getStaticProps and implementing incremental static regeneration (ISR) for improved performance. Currently, my memory usage is ap ...

preserving the current state even after refreshing the page

Currently, I am teaching myself React. When I click on the favorites button, which is represented by a heart symbol, it changes color. However, upon refreshing the page, the color change disappears. To address this issue, I came across the following helpfu ...

Enumerated type alias in Typescript

Within my typings file, I have the following: declare namespace Somatic { enum PropType { html, object, css } } In a separate file named index.ts, I create a shorter alias for this enum like so: type PropType = Somatic.Pr ...

Achievement with ajax: If the status code is 200, execute one function; otherwise, execute a

I can't figure out why this isn't working... I'm using $.ajax to run file.php and pass a POST value from an input field. Even though the file.php is functioning properly (it successfully adds a user to my newsletter), my ajax function seems ...

It is impossible to perform both actions at the same time

Is it possible to create a progress bar using data attributes in JQuery? Unfortunately, performing both actions simultaneously seems to be an issue. <div class="progressbar"> <div class="progressvalue" data-percent="50"></div> </d ...

NodeJS does not support the Array.Push method

I'm having trouble getting this code to work. I want to generate 5 random items from my database and store them in an array called 'dato'. However, when I print the array, it appears to be empty. /* GET users listing. */ router.get('/& ...

Having trouble loading the image source using JSON in Vue.js

var topArticle=new Vue({ el:'#toparticle', data:{topmostArticle:null}, created: function(){ fetch('topnews.json') .then(r=>r.json()) .then(res=>{this.topmostArticle=$.grep(res,functi ...

Is there any benefit to making the SVG elements width and height 100%?

The Angular Material documentation app features an SVG Viewer that is able to scale the SVG content to fit the container using the following function: inlineSvgContent(template) { this.elementRef.nativeElement.innerHTML = template; if (this.sca ...

What is the best way to retrieve an ng-model parameter within a controller?

I'm working on implementing a PUT method in my controller and need to bind the new value back to it. I've tried: <div ng-app="myApp" ng-controller="personCtrl"> <form> First Name: <input type="text" ng-mod ...

Using Switch Case and If Statements in Javascript and Jquery

Can you help me troubleshoot this code? It's designed to detect clicks and keypress events within the #ts_container div for buttons and anchors. The goal is to use an If statement in each case to determine if it's a click or keypress, then update ...

Automatically navigate to a specific selection within the Autocomplete feature

Imagine having a dropdown or Autocomplete list in Material-UI with a long list of items. How can you make the list automatically scroll to a specific item when you open the dropdown? For instance, if we take the list of top100Films, the initial displayed i ...