Salesforce LWC: “Error: Failed to execute ‘removeChild’ on ‘Node’: The node to be removed is not a child of this node. at HTMLDivElement.removeChild”

I recently came across this error when implementing the 3rd party image carousel library called Glider into a Salesforce lightning web component. The message doesn’t give much away, does it? Given the hours I lost investigating the issue I thought I’d share the solution.

Salesforce does not like 3rd party libraries manipulating the DOM. They do make it possible though e.g. if you know that the library is going to inject elements into a container element you can flag that container element like so:

<template>
  <div lwc:dom="manual"></div>
</template>

However, some libraries require that you partially set up an expected DOM structure and then the library’s initialisation sprinkles whatever else it needs within that structure. In my case, Glider injects a “track” (wrapper) <div> around the elements that you can flip through. Interestingly, SF LWC is fine with this unless you are conditionally re-rendering the part of the page that contains Glider. In that case, it fails throwing the above error. My guess is that SF isn’t able to properly clean up because it wasn’t “tracking” the injected <div> – but that’s just a guess.

The solution? Admittedly I got lucky with the 3rd party library since it has a config option to disable the auto-generation of the “track” <div> and manually create it within the expected DOM structure. So I did. And now the component is error-free.

Leave a Comment