2

I'm trying to display "duration" for each video on the page using JavaScript. here is what I've come up with so far:

var vid = document.querySelector(".mhdividdur");
vid.onloadedmetadata = function() {
  var x = document.querySelector(".mhdividdur").duration;
document.querySelector(".mhdi_video_duration").innerHTML = x;
};
<video class="mhdividdur" width="240px" controls preload="metadata" poster="http://cdn1.ko.cowa.ir//kocofeaturedimage.jpg">
<source src="http://cdn1.ko.cowa.ir//hwasa.mp4" type='video/mp4'>
</video>
<p class="mhdi_video_duration"></p>
<video class="mhdividdur" width="240px" controls preload="metadata" poster="http://cdn1.ko.cowa.ir//kocofeaturedimage.jpg">
<source src="http://cdn1.ko.cowa.ir//numb.mp4" type='video/mp4'>
</video>
<p class="mhdi_video_duration"></p>

The problem is that it only returns the duration for the 1st video.

What should I do?

P.S. If there are any other ways except JavaScript to display duration, please give me a hint.

Thank You all

mhdi
  • 90
  • 2
  • 11
  • Instead of querySelector use getElementsByClassName which will return array of elements and you can loop through it and update the duration for each one of them. – Vimal Patel Sep 26 '20 at 13:50
  • i have done this but didn't work! :( – mhdi Sep 26 '20 at 14:29

1 Answers1

3

with querySelector function you can get the first of the elements that match the selector you entered. that's why you need to get all the video elements with querySelectorAll function which will return an array of elements and loop to print their duration.

var videos = document.querySelectorAll(".mhdividdur");
var durationsEl = document.querySelectorAll(".mhdi_video_duration");
for(let i = 0; i < videos.length; i++) {
  videos[i].onloadedmetadata = function() {
    durationsEl[i].innerHTML = videos[i].duration;
  };
}
<video class="mhdividdur" width="240px" controls preload="metadata" poster="http://cdn1.ko.cowa.ir//kocofeaturedimage.jpg">
<source src="http://cdn1.ko.cowa.ir//hwasa.mp4" type='video/mp4'>
</video>
<p class="mhdi_video_duration"></p>
<video class="mhdividdur" width="240px" controls preload="metadata" poster="http://cdn1.ko.cowa.ir//kocofeaturedimage.jpg">
<source src="http://cdn1.ko.cowa.ir//numb.mp4" type='video/mp4'>
</video>
<p class="mhdi_video_duration"></p>
Saar Davidson
  • 1,312
  • 1
  • 7
  • 16
  • sorry, I am a total rookie. I just copy pasted this and nothing happend! even the duration doesn't show up for the 1st video. would you mind helping me through this? – mhdi Sep 26 '20 at 14:33