skip to Main Content

I’m struggling a little bit.

I have multiple elements containing a time in seconds.

<p><time class="replace_time">3.232151</time></p>
<p><time class="replace_time">5.234151</time></p>
...
jQuery(".replace_time").text(function(){
        
    var d = jQuery(this).text();
    
    var h = Math.floor(d / 3600);
    var m = Math.floor(d % 3600 / 60);
    var s = Math.floor(d % 3600 % 60);

    if (h > 0) {       
        return (("0" + h).slice(-2) + ":" + ("0" + m).slice(-2) + ":" + ("0" + s).slice(-2));     
    }
        
    else {    
        return ("0" + m).slice(-2) + ":" + ("0" + s).slice(-2); 
    };
    
});  
  

It’s basically working but unfortunately only for the last (??) item in the DOM order 🤔 What do I overlook?

2

Answers


  1. I think you should use the .each function to get every element

    jQuery(".replace_time").each(function(){
        
        var d = jQuery(this).text();
    
        var h = Math.floor(d / 3600);
        var m = Math.floor(d % 3600 / 60);
        var s = Math.floor(d % 3600 % 60);
    
        if (h > 0) {       
            jQuery(this).text(("0" + h).slice(-2) + ":" + ("0" + m).slice(-2) + ":" + ("0" + s).slice(-2));     
        }
        
        else {    
            jQuery(this).text(("0" + m).slice(-2) + ":" + ("0" + s).slice(-2)); 
        };
    
    });  
    
    Login or Signup to reply.
  2. @ErnestasL has your answer, you need to iterate over the array returned by the initial query.

    If you split out the time formatting part, the rest is pretty simple without jQuery getting in the way:

    // Format seconds as time HH:mm:ss
    function formatTime(secs) {
      let z = n => ('0'+n).slice(-2);
      let h = Math.floor(secs / 3600);
      let m = Math.floor(secs % 3600 / 60);
      let s = Math.floor(secs % 3600 % 60);
      return `${z(h)}:${z(m)}:${z(s)}`;
    }
    
    document.querySelectorAll('.replace_time').forEach(
      el => el.textContent = formatTime(el.textContent)
    );
      
    <p><time class="replace_time">3.232151</time></p>
    <p><time class="replace_time">182735.234151</time></p>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search