Categories
JavaScript Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *