div id에 자식이 있으면 jquery
이 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()
함수는 자식을 포함하는 JQuery 객체를 반환합니다. 따라서 크기를 확인하고 하나 이상의 자녀가 있는지 확인하면됩니다.
이 스 니펫은 요소에 :parent
선택기를 사용하여 자식이 있는지 판별합니다 .
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
}
실제로 Sizzle 엔진을 엄격하게 사용하기 때문에 실제로 가장 빠를 수도 있습니다. 그래도 잘못되었을 수 있습니다. 그럼에도 불구하고 작동합니다.
실제로 이것에 대한 간단한 기본 방법이 있습니다.
if( $('#myfav')[0].hasChildNodes() ) { ... }
여기에는 간단한 텍스트 노드도 포함되므로 a에 해당합니다 <div>text</div>
.
그리고 div를 확인하려면 perticular children이 있습니다 (예 <p>
:
if ($('#myfav').children('p').length > 0) {
// do something
}
div에 특정 자식이 있는지 여부를 확인할 수도 있습니다.
if($('#myDiv').has('select').length>0)
{
// Do something here.
console.log("you can log here");
}
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>
참고 URL : https://stackoverflow.com/questions/1526873/jquery-if-div-id-has-children
'IT' 카테고리의 다른 글
아이폰 사진 보관함에 사진을 저장하는 방법? (0) | 2020.05.12 |
---|---|
matplotlib을 사용하여 두 개의 히스토그램을 동시에 플롯 (0) | 2020.05.12 |
현재 내 애플리케이션을 실행중인 Android API 수준의 휴대 전화를 가져옵니다. (0) | 2020.05.12 |
C 프로그램의 실행 시간 (0) | 2020.05.12 |
Ruby on Rails-CSV 파일에서 데이터 가져 오기 (0) | 2020.05.12 |