반응형
원본 작성일: 2014.09.26
보완 작성일: 2026.02.14

jQuery Selector 정리에 이어서, jQuery Filter를 정리한다. 필터는 선택자 뒤에 :를 붙여서 조건을 추가하는 방식이다.
이 글도 Selector 편과 마찬가지로, Vanilla JS 대응 코드를 함께 정리했다.
인덱스 기반 필터
| jQuery | 설명 | Vanilla JS 대응 |
|---|---|---|
$('li:eq(2)') |
3번째 요소 (0-based) | document.querySelectorAll('li')[2] |
$('li:gt(2)') |
인덱스 2 초과 요소들 | [...document.querySelectorAll('li')].slice(3) |
$('li:lt(2)') |
인덱스 2 미만 요소들 | [...document.querySelectorAll('li')].slice(0, 2) |
$('li:first') |
첫 번째 요소 | document.querySelector('li') |
$('li:last') |
마지막 요소 | [...document.querySelectorAll('li')].at(-1) |
$('li:even') |
짝수 인덱스 (0, 2, 4...) | document.querySelectorAll('li:nth-child(odd)') |
$('li:odd') |
홀수 인덱스 (1, 3, 5...) | document.querySelectorAll('li:nth-child(even)') |
주의: jQuery의
:even/:odd는 0-based 인덱스, CSS의:nth-child는 1-based라서 even/odd가 반대처럼 보인다.
자식 요소 필터
| jQuery | 설명 |
|---|---|
$('li:first-child') |
부모의 첫 번째 자식인 li |
$('li:last-child') |
부모의 마지막 자식인 li |
$('li:nth-child(3)') |
부모의 3번째 자식 (1-based) |
$('li:only-child') |
형제가 없는 li |
이 필터들은 CSS 선택자와 동일하므로 querySelector에서도 그대로 사용 가능하다.
// jQuery
$('li:first-child')
// Vanilla JS (동일 문법)
document.querySelectorAll('li:first-child')상태/내용 기반 필터
| jQuery | 설명 | Vanilla JS 대응 |
|---|---|---|
$(':visible') |
보이는 요소 | 직접 구현 필요 |
$(':hidden') |
숨겨진 요소 | 직접 구현 필요 |
$(':empty') |
비어있는 요소 | querySelectorAll(':empty') |
$('div:has(p)') |
p를 포함한 div | querySelectorAll('div:has(p)') (모던 브라우저) |
$(':contains("텍스트")') |
특정 텍스트 포함 | 직접 구현 필요 |
$(':header') |
h1~h6 선택 | querySelectorAll('h1,h2,h3,h4,h5,h6') |
$(':animated') |
애니메이션 중인 요소 | 해당 없음 (jQuery 전용) |
$(':not(.class)') |
조건 제외 | querySelectorAll(':not(.class)') |
$(':parent') |
자식이 있는 요소 | querySelectorAll(':not(:empty)') (근사) |
:visible / :hidden을 Vanilla JS로
// :hidden 구현
function isHidden(el) {
return el.offsetParent === null;
}
// 숨겨진 요소 모두 찾기
const hidden = [...document.querySelectorAll('*')].filter(isHidden);:contains를 Vanilla JS로
// "텍스트"를 포함한 li 찾기
const items = [...document.querySelectorAll('li')]
.filter(el => el.textContent.includes('텍스트'));jQuery 필터 vs CSS 선택자
jQuery 필터 중 일부(:first-child, :not, :empty)는 CSS 표준이라 querySelector에서 그대로 쓸 수 있다. :has()도 2023년부터 모든 주요 브라우저에서 지원한다.
jQuery 전용 필터(:eq, :gt, :lt, :visible, :contains, :animated)는 CSS에 없는 것이라 Vanilla JS에서는 배열 메서드로 대체해야 한다.
반응형
'Mechanic: IT 인터넷 > Mechanic, M-Tech' 카테고리의 다른 글
| Spring Boot + JPA + MariaDB 연동 시 entityManagerFactory 에러 해결 (0) | 2018.09.18 |
|---|---|
| JavaScript 소수점 자리수 고정 - toFixed() 사용법과 주의점 (0) | 2014.10.07 |
| jQuery Selector 정리 - 선택자 문법과 Vanilla JS 대응표 (1) | 2014.09.25 |
| JavaScript 문자열 자르기 - substring, slice, substr 차이 정리 (0) | 2014.04.08 |
| JavaScript 금액 표시 콤마 - 12345 → 12,345 (0) | 2014.04.08 |