Scan list and compare with an Array in Javascript

Asked

Viewed 29 times

1

I have a list:

<ul id="lista">
    <li><span class="datas">01/01/2020</span></li>
    <li><span class="datas">02/01/2020</span></li>
    <li><span class="datas">03/01/2020</span></li>
    <li><span class="datas">04/01/2020</span></li>
    <li><span class="datas">05/01/2020</span></li>
</ul>

And an Array of dates:

var datas_especiais = ["03/01/2020", "05/01/2020"];

I would like to compare the dates of my array with the dates of my list, if the dates are equal I want to add the event class in the row of my list where the date is equal so that the final result is this

<ul id="lista">
    <li><span class="datas">01/01/2020</span></li>
    <li><span class="datas">02/01/2020</span></li>
    <li class="evento"><span class="datas">03/01/2020</span></li>
    <li><span class="datas">04/01/2020</span></li>
    <li class="evento"><span class="datas">05/01/2020</span></li>
</ul>
  • 1

    What have you ever tried to accomplish?

1 answer

2


I believe you want to do this when the page loads, so I think this might help you.

$(document).ready(function() {

  var datas_especiais = ["03/01/2020", "05/01/2020"];
  
  $('#lista li .datas').each(function(){
  
    var data = $(this).text();
    if (datas_especiais.includes(data)) {
      $(this).parent().addClass('evento');
      $(this).parent().css('color', 'red'); // Somente para identificar visualmente que está funcionando
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="lista">
    <li><span class="datas">01/01/2020</span></li>
    <li><span class="datas">02/01/2020</span></li>
    <li><span class="datas">03/01/2020</span></li>
    <li><span class="datas">04/01/2020</span></li>
    <li><span class="datas">05/01/2020</span></li>
</ul>

  • That’s right, it worked perfectly

Browser other questions tagged

You are not signed in. Login or sign up in order to post.