Cudderz
Cudderz

Reputation: 11

Trying to add a class to a div based on its assigned jQuery index number

I append a series of divs to my $board parent using the following:

    var $board = $('<div id="board"></div>');
    var $row = $('<div class="row"></div>');
    var $cell = $('<div class="box stdBG"></div>')
    var $aRow;
    var $aCell;
    for (var i=0; i < 17; i++){
        $aRow = $row.clone();
        $board.append($aRow);
        for (var j =0; j <25; j++){
            $aCell = $cell.clone();
            $aRow.append($aCell); 
            if (i===8 && j==12){
                $aCell.removeClass('stdBG').addClass('marvin');
                indexI = i;
                indexJ = j;
            }
        }
    } 

This works fine but then I try to add the 'marvin' class to an adjacent div using:

    indexJ += 1;
    $('.row').eq(indexI).find('.cell').eq(indexJ).addClass('marvin');

it doesn't do anything and I don't get any error messages. This rookie needs help!

Upvotes: 0

Views: 44

Answers (2)

Tommy Nguyen
Tommy Nguyen

Reputation: 116

Your problem is here:

.find('.cell')

must be .box instead

$('.row').eq(indexI).find('.box').eq(indexJ).addClass('marvin');

Next time if the same thing happens (no errors on Browser Console), I suggest you to use the watch in Browser Developer Tools to check whether any selectors return the wrong items or not

Upvotes: 0

Kosh
Kosh

Reputation: 18393

Your main problem is that you're looking for .cell class which does not exist. It must have been .box.

$('.row').eq(indexI).find('.cell').eq(indexJ).addClass('marvin');

I've made this snippet and it works fine:

var indexI = 0,
  indexJ = 0;

var $board = $('#board');
var $row = $('<div class="row"></div>');
var $cell = $('<div class="box stdBG"></div>');

for (var i = 0; i < 17; i++) {
  var $aRow = $row.clone();
  $board.append($aRow);
  for (var j = 0; j < 25; j++) {
    var $aCell = $cell.clone();
    $aRow.append($aCell);
    if (i === 8 && j === 12) {
      $aCell.removeClass('stdBG').addClass('marvin');
      indexI = i;
      indexJ = j;
    }
  }
}

indexJ += 1;
$('.row').eq(indexI).find('.box').eq(indexJ).addClass('marvin');
div {
  line-height: 0
}

.box {
  width: 10px;
  height: 10px;
  display: inline-block;
  border: solid 1px #fff
}

.stdBG {
  background: grey
}

.marvin {
  background: pink
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="board"></div>

Upvotes: 1

Related Questions