JQuery - access array error

3

I need to compare two arrays, one with calendar days and one with registered days. When the registered day is corresponding to the value of the innerHTML property of the array of div it should paint the background of this div black:

HTML

<div class="calendar">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
  <div class="item">4</div>
  <div class="item">5</div>

  ...

  <div class="item">31</div>
</div>

<div class="dias-cadastrados">
  <div class="day">4</div>
  <div class="day">21</div>

  ...
</div>

JQuery

var evento      = $(".day");
var eventos_arr = [];
var dias        = $(".item");

for (var i = 0; i < evento.length; i++) {

  eventos_arr[i] = evento[i].innerHTML;

  var count = eventos_arr[i];

  for (var y = 0; y < dias.length; y++) {

    dias[count].style.backgroundColor = "#000"; // output: Uncaught TypeError: Cannot read property 'style' of undefined 

  };

};

The algorithm, besides not doing what it should, returns the error Uncaught TypeError: Cannot read property 'style' of undefined on the line where I apply the style to div . What am I doing wrong?

    
asked by anonymous 02.01.2015 / 22:19

1 answer

3

Being mixing native methods with jQuery methods.

If you want to use jQuery, use .each() if you want to use native or use [0] on each jQuery object or document.querySelectorAll .

In addition I think you have an error in the second loop, which is unnecessary since you never use y .

I suggest using .map() and .get() to change the first collection that jQuery gives in an array, and then use .filter() to get only the elements you want, where you can apply the css you want.

var evento = $(".day");
var dias = $(".item").map(function () {
    return this.innerHTML;
}).get(); // assim ficas com uma array nativa

evento.filter(function (i) {
    return dias.indexOf(this.innerHTML) != -1;
}).css('backgroundColor', "#999");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="calendar">
    <div class="item">1</div>
    <div class="item">2</div>
    <div class="item">3</div>
    <div class="item">4</div>
    <div class="item">5</div>...
    <div class="item">31</div>
</div>
<div class="dias-cadastrados">
    <div class="day">4</div>
    <div class="day">21</div>...</div>

Example in jsFiddle also: link

    
02.01.2015 / 22:30