TryingAtCode
TryingAtCode

Reputation: 175

Check if a div has any children

I have the below code that checks to see if any of my divs has the class "wrong" and if so it shows the jQuery UI dialog box. However i want to extend the code so that it checks those divs and if there are any that are empty it should not show the dialog box.

I've looked around and some people are suggesting using children().length > 0 to accomplish this, but I'm not sure how to write this with my code.

js:

$("#run").click(function() {
  if ($("[id^='Drop']").hasClass("wrong")) {
    $("#dialog1").dialog("open");
  }
});

Upvotes: 4

Views: 213

Answers (3)

Salman Arshad
Salman Arshad

Reputation: 272106

The following selectors could be used to test if an element is empty or not:

  • :empty matches elements that have no children (thus, empty)+
  • :parent matches elements that have children+

Now, rephrasing your statement:

... so that it checks those wrong divs and if there are any that are empty they are all full it should not show the dialog box.

You would write:

var $allWrong = $("id[^='Drop'].wrong"),
    $notEmpty = $wrong.filter(":parent");
if ($allWrong.length && $allWrong === $notEmpty) {
    // show dialog
}

+ Text nodes are counted when counting children. <span> </span> contains a text node which contains a whitespace. Therefore it matches :parent and does not match :empty.

Upvotes: 4

Ja͢ck
Ja͢ck

Reputation: 173562

The logic consists of two parts:

  1. Finding elements with id property starting with "Drop" and having the .wrong class.
  2. Checking whether any of those elements are empty.

To do this, I'm saving the first step in an intermediate variable, before doing the final condition:

var $wrongFields = $('[id^="Drop"].wrong');

if ($wrongFields.length && !$wrongFields.filter(':empty').length) {
    // at least one field exists with:
    // - id starting with "Drop"
    // - class of "wrong"
    // and none of those fields are empty
    $("#dialog1").dialog("open");
}

Demo

Upvotes: 2

Kris
Kris

Reputation: 179

This would also work

$("#run").click(function(){
    if ($("[id^='Drop']").hasClass("wrong") && $("[id^='Drop'].wrong:empty").length ) {
        $( "#dialog1" ).dialog( "open" );
    }
}); 

Upvotes: 0

Related Questions