Mulitple Elements with the same ID

I am trying to use a script on three videos using the same ID (#vid) on the same page. At the moment only one video seems to be able to use the script.

var video = document.getElementById('vid')
// When the 'ended' event fires
video.addEventListener('ended', function(){
  // Reset the video to 
  video.currentTime = 0;
  // And play again
  video.load();
});


Solution 1:

Id must be unique. You should use class instead and then make use of document.getElementsByClassName('className');

var video = document.getElementsByClassName('vid');
var myFunction = function() {
    // Reset the video to 
    this.currentTime = 0;
    // And play again
    this.load();
};

for (var i = 0; i < video.length; i++) {
    video[i].addEventListener('ended', myFunction, false);
}

Solution 2:

The id attribute should be unique otherwise only the first one gets selected always. So use class for a group of elements and iterate over them to attach the event handler.

<script>
  var video = document.getElementsByClassName('vid');
  // convert the element collection to array using Array.from()
  // for older browser use `[].slice.call()` for converting into array
  // and iterate over the elements to attach listener
  Array.from(video).forEach(function(v) {
    v.addEventListener('ended', function() {
      v.currentTime = 0; // or use `this` to refer the element
      v.load();
    });
  })
</script>