Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 138163

JS/Jquery - how to individually select every single matching selector

$
0
0

I'm trying to made a script with Jquery where it finds elements with the class "timeAgo" and replaces its innerHTML with how long ago the time in the create attribute was. Here's what I have:

function timeAgo(time) {
  var d = new Date();
  var diff = Math.floor((d.getTime() - time)/1000);
  if (diff >= 31536000) {
    if (Math.floor(diff/31536000) == 1) {
      return (Math.floor(diff/31536000) + " year ago");
    } else {
      return (Math.floor(diff/31536000) + " years ago");
    }
  } else if (diff >= 2592000) {
    if (Math.floor(diff/2592000) == 1) {
      return (Math.floor(diff/2592000) + " month ago");
    } else {
      return (Math.floor(diff/2592000) + " months ago");
    }
  } else if (diff >= 86400) {
    if (Math.floor(diff/86400) == 1) {
      return (Math.floor(diff/86400) + " day ago");
    } else {
      return (Math.floor(diff/86400) + " days ago");
    }
  } else if (diff >= 3600) {
    if (Math.floor(diff/3600) == 1) {
      return (Math.floor(diff/3600) + " hour ago");
    } else {
      return (Math.floor(diff/3600) + " hours ago");
    }
  } else if (diff >= 60) {
    if (Math.floor(diff/60) == 1) {
      return (Math.floor(diff/60) + " minute ago");
    } else {
      return (Math.floor(diff/60) + " minutes ago");
    }
  } else {
    if (diff == 1) {
      return (diff + " second ago");
    } else {
      return (diff + " seconds ago");
    }
  }
}
$(document).ready(function () {
  $(".timeAgo").innerHTML(timeAgo($(".timeAgo").attr("create")));
}

But whenever I run the code with multiple instances of ".timeAgo", it sets all of them to the first instance of ".timeAgo". How do I make it so that it uses each separate instance?


Viewing all articles
Browse latest Browse all 138163

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>