Search code examples
javascriptvideoplaybackautoplaynodelist

Autoplaying a <video> element using javascript


I have a few elements set up in my html with the autoplay option included. I have found that Chrome doesn't seem particularly willing to autoplay these videos for whatever reason. I'd like to add a bit of javascript to set the video to play once it's loaded. I understand I need to use the play() method on the DOM element in question.

I'm using:

  document.getElementsByTagName('video').play();

This code successfully autoplays my video elements. However, it also throws an error picked up in the console as

Uncaught TypeError: Object #< NodeList > has no method 'play'

I haven't come across this error before and it's stopping the rest of my javascript for executing properly. Any ideas as to what this is and how to resolve it?

Thanks!


Solution

  • That's because getElementsByTagName returns an array of elements so you may specify which element in this array you want.

     document.getElementsByTagName('video')[0].play();
    

    Maybe affecting an id to the <video> element may be better, you can then retreive it by using getElementById(id).