Jquery - error accessing array

Asked

Viewed 77 times

3

I need to compare two arrays, one with calendar days and the other with registered days. When the registered day corresponds to the property value innerHTML of the array of div he must 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 in the line where I apply the style to div. What I’m doing wrong?

1 answer

3


Mixing native methods with jQuery methods.

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

Besides I think you have a mistake in the second loop, which is unnecessary because you never use the y.

I suggest you use the .map() and .get() to exchange the first collection jQuery gives in an array, and then use the .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>
<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>

Example in jsFiddle also: http://jsfiddle.net/b6hb2443/

  • Your algorithm is coloring the background of the Divs with the day class, however I need it to change the color of the div with the item class that matches the number that is written in the Divs with the day class. You can fix that?

  • @Joãopaulosaragossa this is how you want: http://jsfiddle.net/b6hb2443/1/ ? in this case just change the classes.

  • 1

    Thank you very much!

Browser other questions tagged

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