Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
359 views
in Technique[技术] by (71.8m points)

jquery - Using an if statement to check if a div is empty

I'm trying to remove a specific div if a separate div is empty. Here's what I'm using:

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

I think this is close but I can't figure out how to write the code to test of #leftmenu is empty. Any help is appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use .is().

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

Or you could just test the length property to see if one was found.

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

Keep in mind that empty means no white space either. If there's a chance that there will be white space, then you can use $.trim() and check for the length of the content.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...