8

I've found a curious inconsistency when working with HTML5 video.

Compare these two code snippets and take a look at the Elements tab in Chrome developer tools

<body>
  <script>
    const video1 = document.createElement('video');
    video1.autoplay = true;
    video1.muted = true;
    document.body.appendChild(video1);

    const video2 = document.createElement('video');
    video2.setAttribute('autoplay', 'autoplay');
    video2.setAttribute('muted', 'muted');
    document.body.appendChild(video2);
  </script>
</body>

For the first video, muted set using a JS object property wasn't set. For the second one, using setAttribute worked and the DOM attribute is set. Interestingly, this is not the case for autoplay where it behaves consistently.

Why is that? Is there another example of an attribute behaving this way? Is there a rule to this? How does one tell which attribute's property behaves which way in JS except for testing?

Tomáš Hübelbauer
  • 9,179
  • 14
  • 63
  • 125

1 Answers1

8

The attributes are only used to initialize the properties. They do not reflect the current state.

By setting the properties directly, you update the object, but do not affect the dom attributes.

If you set the src of the video (so you can actually see it in action) you will see that the properties have been properly applied

const video1 = document.createElement('video');

video1.src = 'http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4';
video1.controls = true;
video1.autoplay = true;
video1.muted = true;

document.body.appendChild(video1);
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
  • 1
    The code snippet does not work in Google Chrome Version 68, no "muted" attribute in video tag – Anton Malyshev Aug 22 '18 at 11:15
  • 1
    Yes, it is odd. Only the `autoplay` attribute updates in the inspector of Chrome and Firefox, but `muted` and `playsInline` do not. However, the attributes are still in effect (i.e. the video is in fact muted). – fritzmg Nov 23 '21 at 14:00
  • 2
    @AntonMalyshev `video.defaultMuted` is the property that reflects to the muted attribute – luwes Jul 16 '22 at 14:51
  • @luwes thanks so much for the hint to `video.defaultMuted`! – rassoh Oct 13 '22 at 10:11