There is such a html structure:

const timeNodes = Array.from(document.querySelectorAll('[data-time]')); 
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Videos</title> </head> <body> <ul class="videos"> <li data-time="5:43"> Video 1 </li> <li data-time="2:33"> Video 2 </li> <li data-time="3:45"> Video 3 </li> <li data-time="0:47"> Video 4 </li> </ul> </body> </html> 

Help to count or tell me how to find out the duration of all videos. Their duration is specified in the attribute data-time = ""

  • in pure javascript? or jQuery? - Arsen
  • yes better, of course, on pure - spectre_it
  • What is the date time format? Will there be another watch? day month Year? what are the possible options? - Alexey Shimansky
  • @ Alexey Shimansky, for now you need to implement it like this. I think the clock will be. I would like in the decision to lay a little flexibility, hours, days. ... But I think the maximum need hours and then not now. - spectre_it
  • one
    I had an incorrect stack-it answer, as noted by Alexey Shimansky, I could edit it, but as I understand you need to use pure JS, I think Konstantin’s answer will help you) - Arsen

3 answers 3

A pair of functions, the first one counts the number of seconds, the second formats the seconds.

 // Суммируем результаты обработки отдельных строк с помощью reduce const secs = list => list.reduce((sum, str) => { // разбиваем строку по двоеточиям, относимся к результату, как к числу в 60-ричной системе let parts = str.split(':'); // Складываем 60-ричные разряды let q = 1; while (parts.length) { sum += q * parts.pop(); q *= 60; } return sum; }, 0); // Обратная операция, перевод числа секунд в 60-ричный вид. const fmt = secs => { let parts = []; // позиции while (secs > 0) { parts.unshift(secs % 60); // вдвигаем позицию слева secs = secs/60 |0; // целочисленное деление } return parts.map(d => d<10?'0'+d:''+d) // Добавляем ведущие нули .join(':'); } let list = ['1:00:00', '12:55', '00:07']; let sum = secs(list); let time = fmt(sum); console.info(sum, time) 

  • It would be great to see comments on this code, so far most of me personally look like a witch. - Sasha Omelchenko
  • one
    He sprinkled the comments) - vp_arth

On pure js

 var videos = document.getElementsByClassName('videos')[0].children; sumHour = 0; sumMinute = 0; sum = "00:00"; for(var i = 0; i < videos.length; i++) { var clock = videos[i].getAttribute('data-time').split(':'); sumHour += parseInt(clock[0]); sumMinute+=parseInt(clock[1]); } sum = (sumHour + parseInt(sumMinute/60)) + ":" + (sumMinute%60); console.log(sum); 
 <ul class="videos"> <li data-time="5:43"> Video 1 </li> <li data-time="2:33"> Video 2 </li> <li data-time="3:45"> Video 3 </li> <li data-time="0:47"> Video 4 </li> </ul> 

    Of course, after the @vp_arth option, it will be another bike, but suddenly it will be easier for someone to understand the mechanics of translating hours into seconds and back (for example, me).

     const timeNodes = Array.from(document.querySelectorAll('[data-time]')); let seconds = 0, time; timeNodes.forEach(function(item) { // проделываем операцию с каждым элементом массива time = item.dataset.time.split(':').map(Number); // берём из элемента массива значение data-time и формируем массив, попутно приводя тип к числу if (time[time.length-3]) seconds += time[time.length-3]*3600; // если в атрибуте data-time были часы, то переводим их в секунды и добавляем к переменной seconds seconds += time[time.length-1] + time[time.length-2]*60; // таким же образом переводим минуты в секунды и добавляем секунды к seconds }); var output = function normalizeSeconds(seconds) { var result = []; if (seconds >= 3600 ) { // если секунд достаточно для формирования часов var h = Math.floor(seconds / 3600); // получаем к-во часов делением на 3600 и отсекаем дробную часть result.push(h); // записываем в массив var m = Math.floor( (seconds % 3600) / 60 ); // получаем остаток от часов в секундах, получаем к-во минут, отсекаем дробную часть result.push(m); var s = (seconds % 3600) % 60; result.push(s); } else {// если секунд не достаточно для формирования часов var m = Math.floor(seconds / 60); // получаем минуты, отсекая дробную часть от деления на 60 result.push(m); // получаем секунды, остаток от деления на 60 var s = seconds % 60; result.push(s); } return result.join(':'); // соединяем массив в строку через двоеточие } console.log(output(seconds)); 
     <ul class="videos"> <li data-time="5:43"> Video 1 </li> <li data-time="2:33"> Video 2 </li> <li data-time="3:45"> Video 3 </li> <li data-time="1:00:47"> Video 4 </li> </ul>