AD JB Toolbox 01

jQuery / Reference / .has()

.has()는 특정 자손을 포함한 요소만 현재 선택 집합에서 남깁니다. 반환되는 대상은 일치한 자손이 아니라 그 자손을 포함하는 원래 요소입니다.

문법과 적용 범위

$(".card").has(".badge");
$(".card").has(document.getElementById("badge"));

인수는 자손을 찾을 선택자 또는 DOM 요소입니다. 자손은 바로 아래 자식뿐 아니라 더 깊은 단계도 포함합니다. .find()는 조건에 맞는 자손을 반환하지만 .has()는 원래 집합을 필터링합니다. 자기 자신이 조건에 맞는다고 남는 것은 아니므로 현재 요소의 클래스 조건은 .filter()로 검사하세요.

jQuery 공식 문서의 .has() 정의와 인수에서 다른 호출 형태도 확인할 수 있습니다.

전체 실행 예제

아래 코드를 UTF-8 형식의 example.html 파일로 저장한 뒤 브라우저로 여세요. 예제는 jQuery 4.0.0 일반 빌드를 외부 주소에서 불러오므로 인터넷 연결이 필요합니다. 문서가 준비된 뒤 실행하도록 $(function () { ... }) 안에 코드를 작성했습니다.

<!doctype html>
<html lang="ko">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery has 예제</title>
  <style>
    body { margin: 24px; font-family: sans-serif; line-height: 1.6; }
    .marked { background: #fff0b3; border: 2px solid #835b00; }
    .active { color: #a00000; font-weight: bold; }
    button, input, select { font: inherit; }
    #output { white-space: pre-wrap; overflow-wrap: anywhere; }
  </style>
  <script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
</head>
<body>
<div class="card" id="a"><p><span class="badge">공지</span></p></div>
<div class="card" id="b"><p>일반 글</p></div>
<div class="card badge" id="c">자신에게만 badge 클래스</div>
  <p id="output" aria-live="polite"></p>
  <script>
    $(function () {
      const $cards = $(".card").has(".badge");
      $cards.addClass("marked");
      $("#output").text($cards.map(function () { return this.id; }).get().join(", "));
    });
  </script>
</body>
</html>

실행 결과 확인

a 카드만 강조되고 결과는 a입니다. badge가 한 단계 더 안쪽에 있어도 자손이므로 포함되며, c의 badge는 자신에게만 있으므로 조건을 만족하지 않습니다.

사용할 때 주의할 점

  • .has()는 특정 시점의 집합을 반환합니다. 이후 badge를 추가하거나 삭제해도 저장된 집합이 자동 갱신되지는 않으므로 필요할 때 다시 실행하세요.
  • 찾은 badge 자체를 바꾸려면 .find(".badge")를 사용하세요. .has(".badge").addClass(...)는 카드에 클래스를 추가합니다.
  • 인수의 선택자 범위와 원래 집합의 범위를 분리해 생각하면 엉뚱한 조상에 스타일을 적용하는 실수를 줄일 수 있습니다.

용도를 비교하려면 .find()와 반환 대상 비교을 참고하세요.

같은 카테고리의 다른 글
jQuery / Reference / .attr()

jQuery / Reference / .attr()

HTML 속성의 읽기·설정 방법과 반환값을 확인하고, 현재 입력값·체크 상태·ARIA 속성의 처리 차이를 설명합니다.

jQuery / Reference / .slideDown()

jQuery / Reference / .slideDown()

숨겨진 내용을 펼치는 문법과 초기 표시 상태를 설명하고, 효과 큐·완료 콜백·동작 줄이기를 처리하는 예제를 제공합니다.

jQuery / Reference / .width()

jQuery / Reference / .width()

내용 너비와 padding·border를 포함한 너비를 비교하고, border-box에서 width를 읽고 설정하는 결과를 설명합니다.

jQuery / Reference / .after()

jQuery / Reference / .after()

대상의 뒤에 형제 요소를 추가하는 방법과 기존 요소 이동, append 및 insertAfter와의 차이를 설명합니다.

jQuery / Reference / .prependTo()

jQuery / Reference / .prependTo()

삽입할 내용을 먼저 지정해 대상의 첫 번째 자식으로 넣는 방법과 반환 집합, 이동·복제 동작을 설명합니다.

jQuery / Reference / .find()

jQuery / Reference / .find()

현재 요소를 제외한 자손 탐색 범위를 확인하고, children·filter·has와 용도 차이를 설명합니다.

jQuery / Reference / .insertAfter()

jQuery / Reference / .insertAfter()

넣을 요소를 먼저 지정해 대상 뒤에 형제로 삽입하는 문법과 after의 차이, 안전한 텍스트 삽입을 설명합니다.

jQuery / Reference / .val()

jQuery / Reference / .val()

현재 입력값과 다중 선택 값을 읽고 설정하는 방법, change 이벤트와 체크 상태의 차이를 설명합니다.

jQuery / Reference / .addClass()

jQuery / Reference / .addClass()

기존 클래스를 유지하며 한 개 또는 여러 클래스를 추가하는 방법과 CSS가 적용되지 않을 때의 확인 사항을 설명합니다.

jQuery / Reference / .insertBefore()

jQuery / Reference / .insertBefore()

넣을 요소를 먼저 지정해 대상 앞에 형제로 삽입하는 문법과 before의 차이, 이동·복제 동작을 설명합니다.