0
<body>
  <div id="box">
    <script>
      class Sample {
        //
      }
    </script>
  </div>
</body>

In the code above, after deleting the node with the remove() method, Again, the contents of the node were added to the body with the appendChild method. Class repetition declaration error(Uncaught SyntaxError: Identifier 'Sample' has already been declared) occurs. I confirmed that the node was deleted.

How do I delete the node so it doesn't throw an error?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Removing a ` – Bergi May 02 '23 at 04:03
  • What is your [actual problem](https://meta.stackexchange.com/q/66377)? What are you trying to achieve by removing and re-creating the script? – Bergi May 02 '23 at 04:04
  • Dynamically compose the layer screen, load the class for each layer, remove() close the node containing the script when the layer screen is not needed, and open it again when necessary. – user3891813 May 02 '23 at 04:10
  • What "layer screen" are you talking about? Notice it might help not to put any ` – Bergi May 02 '23 at 04:15
  • Load multiple pages in layer form to create a single document structure. If there are a lot of layer pages, the loading time takes longer, so they are being processed dynamically. And when not needed, remove() is used to delete the node. – user3891813 May 02 '23 at 04:36
  • The reason for deleting the dynamically added layers through remove() was that I was concerned that performance would decrease due to resource consumption when many layers are accumulated. – user3891813 May 02 '23 at 04:39

1 Answers1

0

The <script> should not be contained in the box:

<body>
  <div id="box">
  </div>
  <script>
    class Sample {
      //
    }
  </script>
</body>

or

<head>
  …
  <script>
    class Sample {
      //
    }
  </script>
</head>
<body>
  <div id="box">
  </div>
</body>

That way, you can add and remove as many boxes as you want, statically or dynamically. The Sample class should be declared only once, statically, regardless of how many boxes there are.

If you need to execute code for every box, that should not go in a <script> element that is added and removed with the respective box but rather in the code that does add and remove the boxes.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375