admin管理员组

文章数量:1410712

I need to check if an element is empty and if another is NOT empty. The first part of the if works but how do I check if the #dynamicForm element is NOT empty?¨

This obviously doesn't work but I need something like it:

if ($("#formButton").is(':empty') && $("#dynamicForm").is(':notempty')) {
    //do stuff
}

I need to check if an element is empty and if another is NOT empty. The first part of the if works but how do I check if the #dynamicForm element is NOT empty?¨

This obviously doesn't work but I need something like it:

if ($("#formButton").is(':empty') && $("#dynamicForm").is(':notempty')) {
    //do stuff
}
Share edited Oct 6, 2017 at 11:45 glennsl 29.2k12 gold badges59 silver badges79 bronze badges asked Oct 6, 2017 at 0:07 coding_pianistcoding_pianist 812 silver badges12 bronze badges 2
  • Logical NOT operator – Patrick Evans Commented Oct 6, 2017 at 0:11
  • 1 x.is(':not(:empty)') or ! x.is(':empty') ? – Jaromanda X Commented Oct 6, 2017 at 0:11
Add a ment  | 

2 Answers 2

Reset to default 4
if(!$("#dynamicForm").is(':empty')){
     // code here...
}

Note the not operator (!) in front.

First of all you can check if the selected element is empty and negate it:

!$('#dynamicForm').is(':empty')

Furthermore you can check if it's not empty with jquery selector :not:

$('#dynamicForm').is(':not(:empty)')

A third way would be to select all elements, that are not empty and check the length of the jquery collection:

$('#dynamicForm').not(':empty').length

If you need this check in several places you can add your own function to jQuery:

$.fn.notEmpty = function() {
  return !$(this).is(':empty')
}

you can use it like this:

if($('#dynamicForm').notEmpty())

That isn't realy clean and it's not keeping with the jquery conventions. So better extend the selectors instead of extending the functions:

$.extend($.expr[':'],{
  notEmpty:function(c) {
    return !$(c).is(':empty');
  }
});

Now you can use it very straightforward:

if($('#dynamicForm').is(':notEmpty'))

本文标签: javascriptHow do I check if an element is NOT empty with jqueryStack Overflow