divid에 자녀가 있는지 여부를 쿼리합니다.
이것.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 }
if ( $('#myfav').children().length > 0 ) {
// do something
}
이렇게 하면 될 거예요.children()
function은 자식을 포함하는 JQuery 개체를 반환합니다.그래서 당신은 사이즈를 확인하고 적어도 한 명의 아이가 있는지 확인하기만 하면 됩니다.
이 스니펫은 셀렉터를 사용하여 요소에 자식이 있는지 확인합니다.
if ($('#myfav').is(':parent')) {
// do something
}
참고::parent
또한 하나 이상의 텍스트 노드가 있는 요소를 상위 요소로 간주합니다.
그러므로div
의 요소.<div>some text</div>
그리고.<div><span>some text</span></div>
각각 부모로 간주되지만,<div></div>
부모가 아닙니다.
또 다른 선택사항은 다음과 같습니다.
if ( $('#myFav > *').length > 0 ) {
// do something
}
실제로는 JQuery가 아닌 Sizzle 엔진을 엄격하게 사용하기 때문에 가장 빠를 수 있습니다.틀릴 수도 있습니다.그럼에도 불구하고, 효과가 있습니다.
div가 특정한 아이들을 가졌는지 아닌지도 확인할 수 있습니다.
if($('#myDiv').has('select').length>0)
{
// Do something here.
console.log("you can log here");
}
그리고 만약 당신이 디브에게 특정한 아이들이 있는지 확인하고 싶다면 (말씀하세요.<p>
사용:
if ($('#myfav').children('p').length > 0) {
// do something
}
이를 위한 매우 간단한 기본 방법이 있습니다.
if( $('#myfav')[0].hasChildNodes() ) { ... }
여기에는 단순한 텍스트 노드도 포함되므로 다음 기간 동안 해당됩니다.<div>text</div>
.
jQuery way
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>
언급URL : https://stackoverflow.com/questions/1526873/jquery-if-div-id-has-children
'programing' 카테고리의 다른 글
스핀 잠금 구현이 올바르고 최적입니까? (0) | 2023.09.04 |
---|---|
mysql의 모든 테이블에서 모든 행을 비우는 방법(sql) (0) | 2023.09.04 |
PowerShell에서 디렉터리 제외 (0) | 2023.09.04 |
Sinon 오류 이미 래핑된 함수를 래핑하려고 했습니다. (0) | 2023.09.04 |
멀티스레딩 대신 노드 JS 파악 (0) | 2023.09.04 |