How to Properly Unload or Destroy an HTML Element with JavaScript?

Sometimes, we want to properly unload or destroy an HTML element with JavaScript.

In this article, we’ll look at how to properly unload or destroy an HTML element with JavaScript.

Properly Unload or Destroy an HTML Element with JavaScript

To properly unload or destroy an HTML element with JavaScript, we can pause the video, then remove the src attribute from the video element, and then call load again to reload the video element.

For instance, if we have the following HTML video element:

<video src='https://file-examples-com.github.io/uploads/2017/04/file_example_MP4_480_1_5MG.mp4' controls></video>

We can write:

const videoElement = document.querySelector('video');
videoElement.pause();
videoElement.removeAttribute('src');
videoElement.load();

to get the video element with document.querySelector .

Then we call pause to pause the video.

Next, we call removeAttribute with 'src' to remove the src attribute.

And then we call load to reload the video element.

Conclusion

To properly unload or destroy an HTML element with JavaScript, we can pause the video, then remove the src attribute from the video element, and then call load again to reload the video element.