div id에 자식이 있으면 jquery


202

이 if조건은 나에게 문제를 일으키는 것입니다.

if (div id=myfav has children) {
   do something
} else {
   do something else 
}

나는 다음을 모두 시도했다.

if ( $('#myfav:hasChildren') ) { do something }
if ( $('#myfav').children() ) { do something }
if ( $('#myfav:empty') ) { do something }
if ( $('#myfav:not(:has(*))') ) { do something }

답변:


440
if ( $('#myfav').children().length > 0 ) {
     // do something
}

이 작동합니다. 이 children()함수는 자식을 포함하는 JQuery 객체를 반환합니다. 따라서 크기를 확인하고 하나 이상의 자녀가 있는지 확인하면됩니다.


1
답변 해주셔서 감사합니다. 이것이 나를 위해 일한 것입니다. 나는 .children ()과 함께 올바른 길을 가고 있다는 것을 알고 있었지만 무엇이 잘못되었는지 몰랐습니다. 분명히 크기는 0 일 수 있습니다.
— Chris

2
자식에 선택자를 추가하면 요소에 특정 클래스의 자식이 있는지 확인하려는 경우와 같이 요소에 특정 선택자와 일치하는 자식이 있는지 확인할 수도 있습니다.
— Muhd

11
사소한 문제. nitpick에 의미하지 않는다하지만 children().length대신 여기에 jQuery를 워드 프로세서 당 크기 ()의 호출해야합니다 : api.jquery.com/size
— 브라이언 차베스

4
노드에 텍스트 만 포함되어 있다면 어떨까요?
— botenvouwer

1
@sirwilliam 노드는 0 길이로 돌아갑니다.
— Meki

54

이 스 니펫은 요소에 :parent선택기를 사용하여 자식이 있는지 판별합니다 .

if ($('#myfav').is(':parent')) {
    // do something
}

참고 :parent또한 하나 개 이상의 텍스트 노드와 요소를 고려은 부모가 될 수 있습니다.

따라서 와 div안에 있는 요소 는 각각 부모로 간주되지만 부모 는 아닙니다.<div>some text</div><div><span>some text</span></div><div></div>


2
그렇습니다.이 답변은 S Pangborn보다 더 우아하다고 생각합니다. 둘 다 완전히 합법적입니다.
— KyleFarris

1
@Milo LaMar, 성능 차이가별로 없다고 생각하지만 확실한 방법은 시도해 보는 것입니다! 또한 예제 사이 #myfav와 :parent예제에서 공백을 제거해야합니다 . 그렇지 않으면 선택기가 내 답변과 동일하지 않습니다.
— dcharles

3
아주 적은 양의 독서가 저에게 충분했습니다. api.jquery.com/parent-selector 에서 가져옴Additional Notes: Because :parent is a jQuery extension and not part of the CSS specification, queries using :parent cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using :parent to select elements, first select the elements using a pure CSS selector, then use .filter(":parent").
— Milo LaMar

6
0.002s의 성능 테스트 결과-가장 읽기 쉬운 방식이므로이 방법을 선호합니다.
— dtrunk

1
혼란스러워, 이것이 최선의 대답이 아닙니까?
— 안드레이 크리스티안 프로 단

47

또 다른 옵션은 다음과 같습니다.

if ( $('#myFav > *').length > 0 ) {
     // do something
}

실제로 Sizzle 엔진을 엄격하게 사용하기 때문에 실제로 가장 빠를 수도 있습니다. 그래도 잘못되었을 수 있습니다. 그럼에도 불구하고 작동합니다.


16

실제로 이것에 대한 간단한 기본 방법이 있습니다.

if( $('#myfav')[0].hasChildNodes() ) { ... }

여기에는 간단한 텍스트 노드도 포함되므로 a에 해당합니다 <div>text</div>.


$(...)[0] is undefined#myfav찾을 수없는 경우 발생할 수 있습니다 . 해당 조건을 적용하기 전에 첫 번째 일치하는 요소가 있는지 테스트합니다 $('#myfav')[0] && $('#myfav')[0].hasChildNodes().
— CPHPython

13

div를 확인하려면 perticular children이 있습니다 (예 <p>:

if ($('#myfav').children('p').length > 0) {
     // do something
}

7

div에 특정 자식이 있는지 여부를 확인할 수도 있습니다.

if($('#myDiv').has('select').length>0)
{
   // Do something here.
   console.log("you can log here");

}

4

jQuery 방식

jQuery에서 $('#id').children().length > 0요소에 자식이 있는지 테스트하는 데 사용할 수 있습니다 .

데모

var test1 = $('#test');
var test2 = $('#test2');

if(test1.children().length > 0) {
    test1.addClass('success');
} else {
    test1.addClass('failure');
}

if(test2.children().length > 0) {
    test2.addClass('success');
} else {
    test2.addClass('failure');
}
.success {
    background: #9f9;
}

.failure {
    background: #f99;
}
<script src="https://code.jquery.com/jquery-1.12.2.min.js"></script>
<div id="test">
   <span>Children</span>
</div>
<div id="test2">
   No children
</div>


바닐라 JS 방식

jQuery를 사용하지 않으려면 document.getElementById('id').children.length > 0요소에 자식이 있는지 테스트하는 데 사용할 수 있습니다 .

데모

var test1 = document.getElementById('test');
var test2 = document.getElementById('test2');

if(test1.children.length > 0) {
    test1.classList.add('success');
} else {
    test1.classList.add('failure');
}

if(test2.children.length > 0) {
    test2.classList.add('success');
} else {
    test2.classList.add('failure');
}
.success {
    background: #9f9;
}

.failure {
    background: #f99;
}
<div id="test">
   <span>Children</span>
</div>
<div id="test2">
   No children
</div>

당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.