I have been dynamically inserting div elements into the DOM using JavaScript, using the appendChild method to add them and later removing them with removeChild. Strangely, when trying to append a div

There seems to be an issue in the code snippet below. The function create() works fine the first time, but encounters a problem on the second run at the line boxWrapper.appendChild(box);. It appears that the removeChild method is causing some disruption in the parent box-wrapper properties.

function pixels() {
    const value = document.querySelector("#value")
    const input = document.querySelector("#pixels")

    value.textContent = input.value

    input.addEventListener("input", (event) => {
        value.textContent = event.target.value
    })

    return input.value;
}

function create() {

    var elements = document.getElementsByClassName('box'); // get all elements

    let z = elements.length;

    let a = pixels();
    let b = a * a;
    let c = (1 / a) * 100;

    if (z == 0) {

        for (i = 1; i < (b + 1); i++) {
            var boxWrapper = document.getElementById("box-wrapper");

            var box = document.createElement("div");

            box.innerHTML = '1';
            box.style.backgroundColor = "light green";

            var input_percen = c + "%";

            box.style.width = input_percen;
            box.style.height = input_percen;

            box.classList.add("box");

            box.addEventListener('mouseover', function onMouseover(event) {
                event.target.style.backgroundColor = 'black';
            });

            boxWrapper.appendChild(box);   
        }
    } else {
        reset();
    }

}

function reset() {
    while (div = document.getElementById("box-wrapper")) {
        div.parentNode.removeChild(div);

    }
    create();
}

The objective is to clear the contents of box-wrapper and have the ability to append multiple child elements repeatedly.

Answer №1

The reason for the error message is because you are attempting to clear a div that you are also trying to remove:

function reset() {
    while (container = document.getElementById("box-wrapper")) {
        container.parentNode.removeChild(container);
    }
    initialize();
}

You are targeting the parent node of #box-wrapper and then removing the actual #box-wrapper div from its children.

Instead of deleting the div itself, consider simply setting its innerHTML to an empty string:

function reset() {
    container = document.getElementById("box-wrapper");
    container.innerHTML = '';
    
    initialize();
}

Answer №2

If you want to eliminate the div#box-wrapper element from the DOM, you can achieve it using this method:

div.parentNode.removeChild(div);

To clear all child elements inside this div, you have the option of utilizing the replaceChildren() function:

document.getElementById("box-wrapper").replaceChildren();

Answer №3

Appreciate your help! I ended up using:

`function clearBoxes() {

var boxes = document.getElementsByClassName('box'); // selecting all box elements
console.log(boxes.length);
let count = boxes.length;
 for(let i = 0; i < count; i++){
 boxes[0].remove();
 }`  

Grateful for the solution!

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

What could be causing JSON.parse to encounter errors when parsing a string array?

Within the following function, I am utilizing JSON.parse() on specific string arrays saved in window.sessionStorage. This allows me to apply methods like .map(). window.sessionStorage = { myArray1: "["805746|search|4","980093062|search|0","980113648| ...

What steps can be taken to address an undefined error before the execution of useEffect?

Today I encountered a small issue with my online player. It's fetching songs from the database using useEffect and saving them in state like this: const [songs, setSongs] = useState([]); const [currentSong, setCurrentSong] = useState(songs[0]); a ...

Adding Currency Symbol to Tooltip Data in Material-UI Sparklinechart

Below is a SparklineChart example using MUI library: import * as React from 'react'; import Stack from '@mui/material/Stack'; import Box from '@mui/material/Box'; import { SparkLineChart } from '@mui/x-charts/SparkLineCha ...

Attempting to retrieve exclusively the checked records in Vue.js

Currently, I am referring to this library for checkboxes. As I delve into the code, I notice how it is declared and utilized. Initially within the el-table, we have @selection-change="handleSelectionChange". They have initialized an empty array ...

Tips on building an immersive interactive panoramic website

I have a vision for a website that will simulate being in a room, where users can explore the space with limited panoramic views - allowing them to look up/down 30 degrees and left/right 45 degrees. In addition, I would like to integrate interactive object ...

Master the art of horizontal scrolling in React-Chartsjs-2

I recently created a bar chart using react.js and I need to find a way to enable horizontal scrolling on the x-axis as the number of values increases. The chart below displays daily search values inputted by users. With over 100 days worth of data already, ...

When you click on Highcharts, a bigger graph will be displayed

I am working on a feature that allows users to zoom in on small charts on my website. This involves revealing an overlay div and displaying a larger chart with the same data as the clicked chart inside it. function DrawSmallChart() { chart_data = [1, 2, 3 ...

Can we include an option to display all pages in one row on a single page?

Is it possible to include an option to display all rows alongside the current options of 10, 15, and 100? I've been unable to locate this feature in the documentation: Check out the Codesandbox example: https://codesandbox.io/s/muidatatables-custom-t ...

Initializing the $(this) variable prior to the function declaration

I am faced with the task of performing multiple checks based on the IDs of certain elements, all of which vary slightly. So, I created several functions to handle this, and rather than repeatedly using $(this).children ..., I wanted to create a short vari ...

The Angular directive ng-model is not able to return a value

I'm currently troubleshooting an issue with the filters in an older project. Here's the HTML snippet: <input type="text" class="form-control" ng-model="FilterEventsEdit" ng-change="FilterEvents()" ...

Struggling with loading.jsx file in next js version 13.4.5?

Encountered an issue with loading components in next js 13.4.5 layout.jsx "use client"; import React, { Suspense } from "react"; import { ThemeProvider, createTheme } from "@mui/material/styles"; import CssBaseline from " ...

Using jQuery Plugin for Date Operations

I am in search of a jQuery tool that can assist me with date manipulations, such as: 1) Adding a specific number of days to a date and obtaining a new Date. 2) Determining the week of the year for a given date. 3) Calculating the number of days between two ...

When attempting to send data using jQuery to PHP, an issue arises where PHP is unable to receive the information, resulting in an undefined variable

Has anyone successfully sent data from an HTML select to a PHP file using jQuery? I've tried multiple solutions suggested here, but none seem to be working for me. Below is the code I'm using: <select id="city" name="city" > <optgro ...

Discrepancy in Code Outputs

Last night, I spent some time testing out code for basic functions. To preview my work, I used two platforms - Dash and JSFiddle. Everything seemed to be running smoothly on both sites. However, when I uploaded the code to my live website, none of the butt ...

Submitting a form and using Ajax to upload an image

Is there a way to submit an image file to php using ajax without assigning the file to a variable with onchange event? I've tried triggering the request on submit click, but keep getting the error message: "cannot read property 0 of undefined." <ht ...

What is the best way to show a dropdown menu list using my code and JSON response object?

I am currently working on displaying a dropdown list based on the JSON response object. How can I implement it with the code snippet below? in HTML <select class="form-control" name="productCategories[]" id="productCategories< ...

DOJO Dialogue Box Report - Problem

I'm currently facing a challenge with incorporating javascript into the dialog box of my application. Here is an example of the code I am struggling with - var profileDialog1 = new Dialog({ title: "Create Profile", style: "width: 700px;he ...

Remove Request (MongoDB, express, handlebars)

Struggling with implementing a delete request in my application. I have a database filled with reviews that I manipulate through my app. Currently, I'm attempting to create a function that will remove a document from the database and then redirect th ...

The slides in Swiperjs are having trouble moving smoothly

I am experiencing some challenges with swiperjs where the slides are not snapping to the next slide and I am unable to fetch the active index from them. Below is a snippet of my code where I am using typescript, swiperjs version 6.84, and the Ionic frame ...

An error has occurred during runtime due to a TypeError: The application is unable to access properties of an undefined object, specifically 'Upload'. This error has

Greetings to the amazing Stack Overflow Community! Currently, I'm developing a Next.js application that requires me to upload videos to Vimeo. To achieve this functionality, I've implemented tus-js-client for handling the uploads. However, I&apo ...