简体   繁体   中英

How do I check if an element is NOT empty with jquery?

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
}
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'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM