filter()
: 문서 객체를 필터링
$(selector).filter(selector); $(selector).filter(function () {});
필터 선택자
$(document).ready(function () {
$('h3:even').css({
backgroundColor: 'black',
color: 'white'
});
// $('h3') => 6개의 h3 object를 array 형태로 return
// filter(':even') => 6개의 h3 object들 중에서 짝수번째 h3 object 3개 선택
$('h3').filter(':even').css({
backgroundColor: 'black',
color: 'white'
});
$('h3').filter(function (index) {
// index % 3 == 0 => 3의 배수이면 true
return index % 3 == 0;
}).css({
backgroundColor: 'black',
color: 'white'
});
// h1 태그에 모두 orange 배경을 적용
// h1 태그 중 짝수번째만 색상 red로 변경
$('h1').css('background', 'orange').filter(':even').css('color', 'red');
});
end()
: filter() 메서드 제거$(document).ready(function () {
// $('h1').css('background', 'orange');
// $('h1:even').css('color', 'white');
// $('h1:odd').css('color', 'red');
// end() 사용
// $('h1') => h1 object 3개 선택
// filter(':even') => h1 object 3개 중에서 짝수번째인 2개 h1 object선택
// end() : filter 효과를 제거해서 원래 객체 3개를 선택
// filter(':odd') => 3개 중에서 홀수 번째 객체 1개를 선택
$('h1').css('background', 'orange').filter(':even').
css('color', 'white').end().filter(':odd').css('color', 'red');
});
$(document).ready(function () {
// 0 : 첫번째 item 선택
$('h1').eq(0).css('background', 'orange');
// -1 : 마지막 item 선택
$('h1').eq(-1).css('background', 'red');
});
0 ➡ 첫번째
-1 ➡ 맨 마지막
-2 ➡ 뒤에서 2번째
$(document).ready(function () {
// $('h1') => 3개의 h1객체를 선택
// add('h2') => 3개의 h1객체 + 3개의 h2 객체
$('h1').css('background', 'Gray').add('h2').css('color', 'blue');
});
- add 로 추가하기 이전의 css 는 add 로 추가한 요소에는 적용x
- 'h1' 3개에는 'background', 'Gray' 적용
- 'h1' 3개 + 'h2' 3개 모두에 'color', 'blue' 적용
$(document).ready(function () {
// $('h1') => 3개를 선택
$('h1').each(function () {
// class select에 속하는 경우
if ($(this).is('.select')) {
$(this).css('background', 'orange');
}
});
});