Removing children does not work properly; it only removes half of them

Why am I unable to remove all children if I delete half of them in this code? I keep getting an error saying child is not defined, even though I have declared it. Each node in my code has children spheres (nodes) and edges (lines), but when I try to delete them only the nodes get removed. Can anyone assist me with this issue, please?

function onMouseClick( e ) {


    mouseVector.x = 2 * (e.clientX / containerWidth) - 1;
    mouseVector.y = 1 - 2 * ( e.clientY / containerHeight );


    var raycaster = projector.pickingRay( mouseVector.clone(), camera ),
    intersects = raycaster.intersectObjects( scene.children );


    for( var i = 0; i < intersects.length; i++ ) {
        //INTERSECTED = intersects[0].object;

        INTERSECTED = intersects[i].object;
        //obj = intersection.object;

        alert(INTERSECTED.id);

        /*1-*/      //this
        //scene.remove(INTERSECTED);

        /*2-*/      //or this
        for ( c = 0, cl = INTERSECTED.children.length; c < cl; c ++ ) {
            var child = INTERSECTED.children[ c ];
            alert(child.id);
            //child.parent.remove(obj);
            INTERSECTED.remove(child);
            //var lin = scene.children[child.id+1];

            //r lin = scene.getObjectById(child.id+1, true );
            // alert(child.id+1);
            // INTERSECTED.remove(scene.children[child.id+1]);
        }    

        //scene.remove(INTERSECTED);
        scene.add(INTERSECTED);

        animate();
    }
}

Answer №1

It appears that the issue stems from repeatedly looping through an array while simultaneously altering its length. This issue is not specific to three.js but rather a fundamental mistake commonly found in beginner-level JavaScript code.
Consider reworking your code to utilize a while loop instead:

while( INTERSECTED.children.length > 0 ){

    var child = INTERSECTED.children[ 0 ];
    INTERSECTED.remove(child);

}

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

Reduce the use of javascript by incorporating NPM specifically after publishing instead of during the building process

My goal is to minify JS files using NPM commands, but I want the minify command to only run after Post Publish and not on Build. Unfortunately, it currently runs after both build and publish. In my Package.json file, I have the following code: "scripts" ...

What are some techniques for transforming text into JSON format?

Beginner inquiry: I'm struggling with manipulating text using JavaScript. Here is the text I want to transform: "5555 55:55: John: New York 6666 66:66: Jack: Los Angeles" My desired output after manipulation: [{ name:"John", address:"New York", n ...

HTMLMediaElement does not have the setSinkId method

I am currently in the process of developing a WebRTC application using Angular, with the goal of managing audio output through the setSinkId() method within HTMLMediaElement. However, when attempting to use this method, I am encountering an error message s ...

Using AngularJS to extract values from deeply nested JSON structures

I'm currently navigating through a nested JSON object and I'm facing challenges in accessing the sub items within it. Below is a snippet of the JSON file I'm working with. It has successfully passed the JSONLint test, so it should be in pro ...

The jQuery click function triggers immediately upon the loading of the page

Despite my best efforts to resolve this issue independently and conduct extensive research on Google, I am still unable to identify the root of the problem. It seems that the click function continues to activate upon page load. Kindly elucidate the under ...

Why isn't Material UI Data Grid onCellEditCommit working? Wondering if anyone has insight

Having trouble retrieving the data after editing using onCellEditCommit, but it's not functioning properly. This callback is triggered when changes to a cell are committed. Signature: function(params: GridCellEditCommitParams, event: MuiEvent, deta ...

JEST: Troubleshooting why a test case within a function is not receiving input from the constructor

When writing test cases wrapped inside a class, I encountered an issue where the URL value was not being initialized due to dependencies in the beforeAll/beforeEach block. This resulted in the failure of the test case execution as the URL value was not acc ...

Incorporate a JavaScript variable within the src attribute of a script tag

Embedding Google's script allows for displaying a trends Map on our website. <script type="text/javascript" src="//www.google.com.pk/trends/embed.js?hl=en-US&q=iphone&cmpt=q&content=1&cid=TIMESERIES_GRAPH_0&export=5&w=500&a ...

Converting API data in Angular using rxjs

Hey there, I received this response from an API: { "records":[ { "id":1, "motivazione":"", "autorizzazione":false, } ] } Can anyone help me transform it to loo ...

What is the best way to remove the underline in Material-UI while still keeping the selection feature intact in Autocomplete?

Seeking to develop an Autocomplete feature with the TextField component while eliminating the underline. I successfully disabled the underline by utilizing InputProps={{ disableUnderline: true }} in the TextField properties, however, it also eliminated t ...

Autocomplete with Avatar feature in Material UI TextField

Is it possible to display an avatar in the text field of the autocomplete material-ui component when using the getOptionLabel prop, which only accepts a string? The expected UI shows a profile picture and name for each option. Can we achieve the same thi ...

Dynamic Bootstrap Modal Widget

I have been attempting to create a dynamic modal using Twitter Bootstrap as shown below: $('#myModal').on('hide', function () { $(this).removeData('modal'); $('.loading-modal').remove(); }) Although it rel ...

A method for displaying both the next and previous steps without relying on a switch case statement

I have an array list as follows: const data = [ { title: 'Title1', }, { title: 'Title2', }, { title: 'Title3', }, { title: 'Title4', ...

Encountering a type mismatch error in Typescript while working with Redux state in a store file

It appears that I have correctly identified all the types, but could there be a different type of Reducer missing? 'IinitialAssetsState' is not assignable to type 'Reducer' The complete error message: Type '(state: { assets: n ...

Ways to extract information from a JSON array based on its length and content

Here is an example of some data: { "_id": ObjectId("528ae48e31bac2f78431d0ca"), "altitude": "110", "description": [ { "id": "2", "des": "test" } ], "id": "1", "latitude": "24.9528802429251", ...

What is the best way to include a JavaScript function in a dynamically generated div?

By clicking a button, I am able to dynamically generate a table row that contains a div element with the class "contents." $(document).on("click", ".vote", function() { // Removing selected row var rowLoc = this.parentNode.parentNode. ...

The icon is being displayed as text instead of the actual Fontawesome icon

Using jquery version 3.3.1 I am dynamically creating an anchor tag: let link = $("<a>"); link.attr("href", "#"); link.text("My anchor" + ' <i class="fas fa-people-carry"></i>'); However, when I try to display ...

What is the best way to save the raw text or event-stream data from a JavaScript get request when the server is continuously loading?

Currently, I'm attempting to fetch some basic data from an API. Here is the URL for the request: The issue lies in the fact that the server appears to keep refreshing the page constantly. This endless loading occurs both when using a browser and with ...

The AJAX request to fetch XML data resulted in a failure to redirect as intended

I'm encountering an issue with redirection after retrieving the XML data. The scenario involves a login process that fetches the ID values for username and password, verifies their existence, and then displays the alert "worked." However, despite show ...

Select one href by clicking and apply addClass

I have a one-page HTML document with links in the header. I want to make it so that when I click on a link (<a>), only that specific link changes its class to (.links). I've tried various methods, but the current jQuery method I'm using ad ...