IT story

if 문을 사용하여 div가 비어 있는지 확인

hot-time 2020. 8. 4. 22:50
반응형

if 문을 사용하여 div가 비어 있는지 확인


별도의 div가 비어 있으면 특정 div를 제거하려고합니다. 내가 사용하는 것은 다음과 같습니다.

$(document).ready(function () {
    if ('#leftmenu:empty') {
        $('#menuTitleWrapper').remove();
        $('#middlemenu').css({ 'right': '0', 'position': 'absolute' });
        $('#PageContent').css({ 'top': '30px', 'position': 'relative' });
    }
});

나는 이것이 가깝다고 생각하지만 #leftmenu의 테스트 코드가 비어있는 방법을 알 수 없습니다. 도움을 주셔서 감사합니다!


사용할 수 있습니다 .is().

if( $('#leftmenu').is(':empty') ) {
    // ...

또는 length속성을 테스트하여 속성이 있는지 확인할 수 있습니다.

if( $('#leftmenu:empty').length ) {
    // ...

비워두면 공백이 없다는 것을 명심하십시오 . 공백이있을 가능성이있는 $.trim()경우 컨텐츠 길이를 사용 하고 확인할 수 있습니다 .

if( !$.trim( $('#leftmenu').html() ).length ) {
    // ...

그것은 당신이 비어있는 의미에 달려 있습니다.

텍스트가 없는지 확인하려면 (자체가 비어있는 자식 요소를 허용) :

if ($('#leftmenu').text() == '')

자식 요소 나 텍스트가 없는지 확인하려면

if ($('#leftmenu').contents().length == 0)

또는,

if ($('#leftmenu').html() == '')

빠른 데모를 원한다면 빈 div를 확인하는 방법을 알려면이 링크를 사용해보십시오.

http://html-tuts.com/check-if-html-element-is-empty-or-has-children-tags/


다음은 몇 가지 간단한 예입니다.

CSS 사용

공백이 없어도 div가 비어 있으면 CSS를 사용할 수 있습니다.

.someDiv:empty {
    display: none;
}

불행히도 이전 형제 요소를 선택하는 CSS 선택기가 없습니다. 다음 형제 요소에만 있습니다.x ~ y

.someDiv:empty ~ .anotherDiv {
    display: none;
}

jQuery 사용

text () 함수를 사용하여 요소의 텍스트 길이 확인

if ( $('#leftmenu').text().length == 0 ) {
    // length of text is 0
}

엘리먼트에 자식 태그가 있는지 확인하십시오

if ( $('#leftmenu').children().length == 0 ) {
    // div has no other tags inside it
}

공백이있는 경우 빈 요소 확인

if ( $.trim( $('.someDiv').text() ).length == 0 ) {
    // white-space trimmed, div is empty
}

다음 과 같이 jQuery 기능을 확장 할 수 있습니다 .

연장 :

(function($){
    jQuery.fn.checkEmpty = function() {
       return !$.trim(this.html()).length;
    };
}(jQuery));

사용하다 :

<div id="selector"></div>

if($("#selector").checkEmpty()){
     console.log("Empty");
}else{
     console.log("Not Empty");
}

이 시도:

$(document).ready(function() {
    if ($('#leftmenu').html() === "") {
        $('#menuTitleWrapper').remove();
        $('#middlemenu').css({'right' : '0', 'position' : 'absolute'});
        $('#PageContent').css({'top' : '30px', 'position' : 'relative'});
    }
});

가장 예쁘지는 않지만 작동해야합니다. innerHTML (#leftmenu의 내용)이 빈 문자열인지 확인합니다 (즉, 내부에 아무것도 없음).


In my case I had multiple elements to hide on document.ready. This is the function (filter) that worked for me so far:

$('[name="_invisibleIfEmpty"]').filter(function () {
    return $.trim($(this).html()).length == 0;
}).hide();

or .remove() rather than .hide(), whatever you prefer.

FYI: This, in particular, is the solution I am using to hide annoying empty table cells in SharePoint (in addition with this condition "|| $(this).children("menu").length".


if (typeof($('#container .prateleira')[0]) === 'undefined') {
    $('#ctl00_Conteudo_ctrPaginaSistemaAreaWrapper').css('display','none');
}

I've encountered this today and the accepted answers did not work for me. Here is how I did it.

if( $('#div-id *').length === 0 ) {
    // your code here...
}

My solution checks if there are any elements inside the div so it would still mark the div empty if there is only text inside it.


if($('#leftmenu').val() == "") {
   // statement
}

참고URL : https://stackoverflow.com/questions/4665466/using-an-if-statement-to-check-if-a-div-is-empty

반응형