If any div is empty, do something

I have an instruction below that checks if any of the Divs with id #Drop are empty, if one of them is empty, it shows a warning. however, at present, when any div has content inside it, the statement no longer works.

I suppose I'm trying to say that I want it to appear if the ANY div is empty. There are 4 Divs in total, and if any of them is empty, a warning message should appear, it does not matter if, for example, 3 of 4 contents, a warning should appear whenever there is an empty div.

HTML:

<div id="Drop1" ondrop="drop(event)" ondragover="allowDrop(event)"></div> <div id="Drop2" ondrop="drop(event)" ondragover="allowDrop(event)"></div> <div id="Drop3" ondrop="drop(event)" ondragover="allowDrop(event)"></div> <div id="Drop4" ondrop="drop(event)" ondragover="allowDrop(event)"></div> 

JS:

 $("#run").click(function(){ if ($("[id^='Drop']").html() === ""){ alert("empty")// ... } }); 
+5
source share
4 answers

use the jQuery :empty selector. more about :empty selector.

Description: Select all items that do not have children (including text nodes).

check out demo

  $("#run").click(function(){ if ($("[id^='Drop']:empty").length){ alert("empty")// ... } }); 

Second option: as I mentioned in my comment, and @A. Wolff mention in the comment of the answer here, I add the second option

Demo

 $("#run").click(function(){ if ($("[id^='Drop']").is(":empty")){ alert("empty")// ... }; }); 
+5
source

 $("#run").click(function(){ if ($("[id^='Drop']").is(":empty")){ alert("empty")// ... }; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="run">click</div> <div id="Drop1" ondrop="drop(event)" ondragover="allowDrop(event)"></div> <div id="Drop2" ondrop="drop(event)" ondragover="allowDrop(event)"></div> <div id="Drop3" ondrop="drop(event)" ondragover="allowDrop(event)"></div> <div id="Drop4" ondrop="drop(event)" ondragover="allowDrop(event)"></div> 
+2
source

You can try something like this too

 $('div').each(function(index){ if($(this).text() == ''){ index=parseInt(index+1 ,10) alert('The div at '+index+' is empty') } }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <div id="Drop1" ondrop="drop(event)" ondragover="allowDrop(event)"></div> <div id="Drop2" ondrop="drop(event)" ondragover="allowDrop(event)"></div> <div id="Drop3" ondrop="drop(event)" ondragover="allowDrop(event)"></div> <div id="Drop4" ondrop="drop(event)" ondragover="allowDrop(event)">text</div> 
+1
source

Try it,

 for(i=0;i<=4;i++) { if($("div#Drop"+i).length==0) { alert("DIV with id Drop"+i+"is empty"); return false; } } 
0
source

All Articles