mwrogers
mwrogers

Reputation: 5

Hide just one item in a list based on date with JavaScript

I have a list with dates:

<ul>
      <li class="demo">2021-01-07</li>
      <li class="demo">2021-03-23</li>
      <li class="demo">2021-03-20</li>
      <li class="demo">2021-05-20</li>
</ul>

I want list items that are older than today's date to be hidden. In this case (today is Feb. 12, 2021), it would be the first item.

Here is what I tried:

var expiretext = $(".demo").html();
var expire = new Date(expiretext);
var now = new Date();
if (now > expire) {
  $(".demo").hide();
}

This hides all the items. How do I hide only the item with the passed date?

Upvotes: 0

Views: 156

Answers (2)

ikiK
ikiK

Reputation: 6532

Also read about JS date formats here to be more precise and apply adiitonal logic if needed:

Converting a string to a date in JavaScript

And additional useful info for you:

What's the best way to loop through a set of elements in JavaScript?

document.querySelectorAll("ul li.demo").forEach( li => {
  let dat = new Date(li.innerText)
  let currentdate = new Date();
  if (dat < currentdate){li.style.display="none"}
});
<ul>
  <li class="demo">2021-01-07</li>
  <li class="demo">2021-03-23</li>
  <li class="demo">2021-03-20</li>
  <li class="demo">2021-05-20</li>
</ul>

Upvotes: 1

Doan Van Thang
Doan Van Thang

Reputation: 997

When you select .demo, It returns a list. Which you should loop each of them

var now = new Date();
$(".demo").each((idx, ele) => {
    let expire = new Date($(ele).text());
    if (now > expire) {
        $(ele).hide();
    }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
    <li class="demo">2021-01-07</li>
    <li class="demo">2021-03-23</li>
    <li class="demo">2021-03-20</li>
    <li class="demo">2021-05-20</li>
</ul>

Upvotes: 0

Related Questions