jQuery addClass example

Change class name on click in jQuery

by tea4two

HTML

<div class="box">
  <div class="child">子供</div>
  <div class="child">子供</div>
  <div class="child">子供
    <div class="child">孫</div>
  </div>
</div>

CSS

.box {
  background-color: purple;
  padding: 20px;
  background-color: brown;
  border-radius: 5px;
}
.box > .child {
  background-color: yellow;
  margin-bottom: 20px;
  padding: 10px;
}
.child .child {
  background-color: green;
  color: #fff;
  padding: 5px;
}

JavaScript

var $box = $('.box');
var $boxfiltered = $box.filter('.child');
var $child = $('.child');
var $childfiltered = $child.filter('.child');

console.log($boxfiltered); // 取得されない
console.log($childfiltered); // 取得OK

$boxfiltered.css('background', 'pink');
// $childfiltered.css('background', 'pink');