7

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
  • 5,273
  • 8
  • 46
  • 86

1 Answers1

7

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
  • 173,972
  • 30
  • 239
  • 291