Javascript Adds Same Class To Divs Without Calculating For Each Div

jquery find class
add class to each element jquery
jquery each
jquery get all elements with class
jquery parent
jquery selector
jquery class selector
jquery select all

I have 2 coupons showing, they both have the .new-coupon when in fact one should say .new-coupon and one should say .old-coupon. It seems to apply the same class for every element on the page with that class instead of calculating which class it should be for each element.

jQuery(document).ready(function($) {
// Set the date we're counting down to
  var deadlineYear = $("#clockdiv .year").attr("rel");
  var deadlineMonth = $("#clockdiv .month").attr("rel");
  var deadlineDay = $("#clockdiv .days").attr("rel");
  var deadlineHour = $("#clockdiv .hours").attr("rel");
  var deadlineMinute = $("#clockdiv .minutes").attr("rel");
  var deadlineSecond = $("#clockdiv .seconds").attr("rel");
  var couponExpired = $("#clockdiv").attr("rel");

  var countDownDate = new Date(deadlineYear + "/" + deadlineMonth + "/" + deadlineDay + " " + deadlineHour + ":" + deadlineMinute + ":" + deadlineSecond).getTime();

  // Update the count down every 1 second
  var x = setInterval(function() {

// Get todays date and time
var now = new Date().getTime();

// Find the distance between now and the count down date
var distance = countDownDate - now;

// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);

// Output the result in an element with id="demo"

document.getElementById("days").innerHTML = days;
document.getElementById("hours").innerHTML = hours;
document.getElementById("minutes").innerHTML = minutes;
document.getElementById("seconds").innerHTML= seconds;

// If the count down is over, write some text 
if (distance < 0) {
    clearInterval(x);
    document.getElementById("clockdiv").innerHTML = "<p>" + couponExpired + "</p>";
}

var startDate = $("#clockdiv .start").attr("rel"); //2018/09/28 17:00:00

  var startDateNew = new Date(startDate);
  var newOldDate = new Date(startDateNew.setDate(startDateNew.getDate() + 7));
  var nowDateNew = new Date(now);

  if (days <= 7) {
      $('.couponDiv').addClass("old-coupon");
  } else if ((nowDateNew.getTime() - newOldDate.getTime()) < 0) {
      $('.couponDiv').addClass("new-coupon");
  }    
  }, 1000);
});

HTML used for variables:

<div id="clockdiv" rel="'.$expired.'">
<span class="start" rel="'.$start.'"></span>
<span class="year" rel="'.$year.'"></span>
<span class="month" rel="'.$month.'"></span>
<div><span id="days" class="days" rel="'.$day.'"></span><div class="smalltext">Days</div></div>
<div><span id="hours" class="hours" rel="'.$hour.'"></span><div class="smalltext">Hours</div></div>
<div><span id="minutes" class="minutes" rel="'.$minute.'"></span><div class="smalltext">Minutes</div></div>
<div><span id="seconds" class="seconds" rel="'.$second.'"></span><div class="smalltext">Seconds</div></div>
</div>

HTML used for displaying the coupons on the offers page:

<li>
                    <?php
                    $year = DateTime::createFromFormat('Y-m-d H:i:s', get_field('offer_voucher_deadline'))->format('Y');
                    $month = DateTime::createFromFormat('Y-m-d H:i:s', get_field('offer_voucher_deadline'))->format('m');
                    $day = DateTime::createFromFormat('Y-m-d H:i:s', get_field('offer_voucher_deadline'))->format('d');
                    $hour = DateTime::createFromFormat('Y-m-d H:i:s', get_field('offer_voucher_deadline'))->format('H');
                    $minute = DateTime::createFromFormat('Y-m-d H:i:s', get_field('offer_voucher_deadline'))->format('i');
                    $second = DateTime::createFromFormat('Y-m-d H:i:s', get_field('offer_voucher_deadline'))->format('s');

                    $humanDate = DateTime::createFromFormat('Y-m-d H:i:s', get_field('offer_voucher_deadline'))->format('D jS M Y');
                    $expiredText = get_field('offer_voucher_expired');
                    ?>
                <div style="display:none;">
                    <?php echo do_shortcode('[gw-countdown expired="'.$expiredText.'" year="'.$year.'" month="'.$month.'" day="'.$day.'" hour="'.$hour.'" minute="'.$minute.'" second="'.$second.'" start="'.get_field('offer_voucher_start').'"]');?>
                </div>
                <div id="couponDiv" class="couponDiv">
                    <h1><?php the_title();?></h1>
                    <div class="couponDetails">
                        <div class="couponView">
                            <?php $offer = get_field('offer_single_label', 'options'); $offerC = ucwords($offer);?>
                            <a class="button" href="<?php the_permalink();?>" title="See Offer Details">See <?php echo $offerC;?> Details</a>
                        </div>
                        <div class="couponValid">
                            <p class="bold">Valid Until:</p>
                            <p class="couponDate"><?php echo $humanDate;?></p>
                        </div>
                    </div>
                </div>
                </li>

Edit

I understand completely where the issue lies, and have updated the code to the following:

$('.couponDiv').each(function() {

    var startDate = $("#clockdiv .start").attr("rel"); //2018/09/28 17:00:00
    var startDateNew = new Date(startDate);
    var newOldDate = new Date(startDateNew.setDate(startDateNew.getDate() + 7));
    var nowDateNew = new Date(now);


    if (days <= 7) {
        $(this).addClass("old-coupon");
    } else if ((nowDateNew.getTime() - newOldDate.getTime()) < 0) {
        $(this).addClass("new-coupon");
    }
  }); 

However, I do not know how to make:

var startDate = $("#clockdiv .start").attr("rel");

Apply to $this so its $this #clockdiv .start because then it will work I believe...

Edit

I have altered a line of code to read:

var startDate = $(this).find("#clockdiv .start").attr("rel");

This now only adds the class to the first offer and not the 2nd offer, I then tried repeating the:

$(this).find()

Around the initial variables and then moved the:

$('.couponDiv').each(function() {

To the top below the document ready function however, this stopped any class being added.

if (days <= 7) {
   $('.couponDiv').addClass("old-coupon");
} else if ((nowDateNew.getTime() - newOldDate.getTime()) < 0) {
   $('.couponDiv').addClass("new-coupon");
}

In your codes above, you had selected all of .couponDiv to add class old-coupon and once again you select all of .couponDiv to add class new-coupon. The conditions have no meaning here because with any matching you still add class for all elements.

You must separate which elements are belong to "old" and with elements are belong to "new". Then add the respectively class name.

How to Loop Through Elements with the Same Class in jQuery, I have 2 coupons showing, they both have the .new-coupon when in fact one should say .new-coupon and one should say .old-coupon. It seems to apply the  Read more posts by this author. Contains visual diagrams for every single CSS property in common use. [ Check out CSS Visual Dictionary with all CSS properties explained visually.] In this tutorial, we’ll take a look at how to call JavaScript code on multiple DIV elements on the page, when they are missing the id attribute ( or when calling

Is this what you need?

var startDate = $(this).find("#clockdiv .start").attr("rel"); //2018/09/28 17:00:00

Equalize Heights of Divs, How to Loop Through Elements with the Same Class in jQuery The jQuery code in the following example will loop through each DIV elements and highlight <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> How to add CSS properties to an element dynamically using jQuery · How to display all items or  I'm attempting to grab the text in each testclass and create a list, like so: Banana Oranges Oranges Peaches Peaches Watermelons What I'm struggling with is replacing the numbers with either nothing, or inserting a new entry into the list with a duplicate.

After some reconstructing and work with $this I was able to get this working:

$('.couponWrap .coupons li').each(function() {
    // Set the date we're counting down to
    var deadlineYear = $(this).find("div .clockdiv .year").attr("rel");
    var deadlineMonth = $(this).find("div .clockdiv .month").attr("rel");
    var deadlineDay = $(this).find("div .clockdiv .days").attr("rel");
    var deadlineHour = $(this).find("div .clockdiv .hours").attr("rel");
    var deadlineMinute = $(this).find("div .clockdiv .minutes").attr("rel");
    var deadlineSecond = $(this).find("div .clockdiv .seconds").attr("rel");
    var couponExpired = $(this).find("div .clockdiv").attr("rel");

    var countDownDate = new Date(deadlineYear + "/" + deadlineMonth + "/" + deadlineDay + " " + deadlineHour + ":" + deadlineMinute + ":" + deadlineSecond).getTime();
    var startDate = new Date($(this).find("div .clockdiv .start").attr("rel"));

    var self = $(this);

    // Update the count down every 1 second
    var x = setInterval(function() {

      // Get todays date and time
      var now = new Date().getTime();

      // Find the distance between now and the count down date
      var distance = countDownDate - now;

      // Time calculations for days, hours, minutes and seconds
      var days = Math.floor(distance / (1000 * 60 * 60 * 24));
      var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
      var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
      var seconds = Math.floor((distance % (1000 * 60)) / 1000);

      // Output the result in an element with id="demo"

      document.getElementById("days").innerHTML = days;
      document.getElementById("hours").innerHTML = hours;
      document.getElementById("minutes").innerHTML = minutes;
      document.getElementById("seconds").innerHTML= seconds;

      // If the count down is over, write some text 
      if (distance < 0) {
        clearInterval(x);
        document.getElementById("clockdiv").innerHTML = "<p>" + couponExpired + "</p>";
      }

      //Works but only for 1st start date
      //var testDate = $("div .clockdiv .start").attr("rel"); //2018/09/28 17:00:00

      var startDateNew = new Date(startDate);
      var startDateNewer = new Date(startDate);
      var newOldDate = new Date(startDateNewer.setDate(startDateNew.getDate() + 7));

      //alert(startDate + ", " +  startDateNew + ", " + startDateNewer + ", " + newOldDate);

      //This works fine
      var nowDateNew = new Date().getTime();

      //alert(nowDateNew - newOldDate.getTime());

      if (days <= 7) {
        self.find('div.couponDiv').addClass("old-coupon");
      } else if ((nowDateNew - newOldDate.getTime()) < 0) {
        self.find('div.couponDiv').addClass("new-coupon");
      }
    }, 1000);
  });

Don't Overthink It Grids, They have courses on all the most important front-end technologies, from React to CSS, from Vue to D3, and beyond with Node.js and Full Stack. hard drive, but when I uploaded the files to the server, for some reason the script didn't work in the same manner. It actually set the height for each div to the height of the first. Set default value for struts 2 autocompleter. jquery,jsp,struts2,struts2-jquery,struts2-jquery-plugin. You should use the value attribute as suggested by @Choatech: value false false String "Preset the value of input element."

.find(), They may not explicitly have a grid system in place, but if they have a "main content area" A block level element is as wide as the parent it's inside ( width: auto; ). We just make two column divs with appropriate class names. The second step is applying a fixed padding to the right side of all columns except the last one. In the code you're using jQuery only to add class names, which could easily be done with plain JavaScript. Browser compatibility .append() isn't supported by any version of Microsoft or Android browsers so if you're targeting any of those browsers you'll have to use other methods, add a polyfill , or use jQuery.

:visible Selector, Description: Get the descendants of each element in the current set of The first signature for the .find() method accepts a selector expression of the same type that we can pass to though item II matches the selector expression, it is not included in the results; <script src="https://code.jquery.com/jquery-3.5.0.js"></​script>. With that markup, if you do containerDiv.getElementsByTagName("DIV"); you will get all divs in the hierarchy, whether they are subrows or whatever.

jQuery :nth-child() Selector, Tracking the visibility of elements via other methods, using a class for example, can provide better performance. Example: Make all visible divs turn yellow on click. My HTML code has four divs with same class name that is testdiv and inside each div there are three input boxes. I would really appreciate the help. Posted 16-Jan-13 8:25am

Comments
  • Is there something in each .coupon that you can use to evaluate new or old? Right now you seem to be using the same dates/times for the calculation for all coupon. HTML would be helpful to assist.
  • @Steve0 I have added all relevant HTML/PHP
  • You're only doing a date calculation one time for the entire application, rather than redoing the calculation with different dates for each coupon. Also you have both id="couponDiv" and class="couponDiv" this is bad, two elements cannot have the same id
  • @Our_Benefactors I know this, that's why I am asking how to run it more than once for each coupon?
  • @DanielVickers you need to use jQuery.each()
  • I appreciate the pointer but I know the issue just not know how to resolve it and as mentioned in the bounty: "I am looking for a solution not a pointer. Much appreciated."
  • I added this and then it only added the class to the first offer and not the 2nd offer, I then tried adding the .each() after the first line and then adding $this().find... for all the variables and it stopped adding all the classes.
  • Actually testing it, this half works it solves that problem but now $days is the same for each coupon so I need everything to calculate for .each() but it's not working when i move the function above the code.