Modify outerHTML of video element without destroying video

Viewed 79

I'm working on a Firefox extension that deals with adding overlay to video elements. I'm using https://www.w3schools.com/html/mov_bbb.mp4 as an isolated example to test on. However, if I say something like:

$0.outerHTML = $0.outerHTML;

in the console, the video stops playing and disappears, leaving only the box shadow. Note that I do not get this behavior on a regular webpage. I also don't get this behavior in Chrome.

I'd like to add my UI elements, but I can't figure out a workaround.

1 Answers

It's not clear what kind of stuff you're trying to do with the video itself. But, I would first try and get away with CSS. If you really want to rip out the video and then wrap it in your own HTML and put it back where it was, you can do this:

// Get reference to the video element
const videoElement = document.getElementsByTagName('video')[0];
// Clone the element
const videoClone = videoElement.cloneNode(true);
// Create your new container
const videoContainer = document.createElement('div');
// Do what you want with the new container
const someHeading = document.createElement('h1');
someHeading.innerText = 'This is a video';
// Append stuff to the new container
videoContainer.append(someHeading);
// Append the cloned video to the new container
videoContainer.append(videoClone);
// Remove the old video
videoElement.remove();
// Append your new video container with cloned video
document.body.append(videoContainer);
<video width="320" height="240" controls>
  <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
  Your browser does not support the video tag.
</video>

Setting outerHTML will just overwrite the HTML. You can play around with the setting of innerHTML and outerHTML if you want to see the difference, but in your case, it's probably the same outcome.

Related