Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if any Div is empty do something

I have the below statement that checks to see if any of the Divs with id #Drop are empty, if one is empty it shows an alert. however currently when any div has content inside it the statement no longer works.

I guess what I'm trying to say is that i want it so an alert shows up if ANY div is empty. There are 4 Divs in total and if any one of them is empty the alert message should appear, it doesn't matter if for example 3 of the 4 have content the alert should trigger 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")// ...
    }
});
like image 658
TryingAtCode Avatar asked Apr 18 '15 10:04

TryingAtCode


People also ask

What does an empty div do?

Empty or superfluous DOM elements are generally regarded as bad. They add page weight, can cause accessibility issues, and are generally a hacky solution. We have more appropriate tools (CSS margin-top) to handle spacing like this. Someone might delete that empty 60px div thinking it serves no purpose.

How do you test if an element is empty?

This method can be used on this element to test if it is empty by using “:empty” selector. The “:empty” selector is used to select all the elements that have no children. It will return true if the element is empty, otherwise, return false.

How do I check if a div has content?

To check if a div element contains specific text:Use the textContent property on the element to get the text content of the element and its descendants. Use the includes() method to check if the specific text is contained in the div . If it is, the includes() method returns true , otherwise false is returned.

Is (': Empty ') in jQuery?

jQuery empty() MethodThe empty() method removes all child nodes and content from the selected elements. Note: This method does not remove the element itself, or its attributes. Tip: To remove the elements without removing data and events, use the detach() method.


1 Answers

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

Description: Select all elements that have no children (including text nodes).

check DEMO

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

Second option : as i have mention in my comment and @A. Wolff mention in answer comment here i add second option

DEMO

$("#run").click(function(){       
    if ($("[id^='Drop']").is(":empty")){
     alert("empty")// ...
    };
});
like image 149
Nishit Maheta Avatar answered Oct 21 '22 04:10

Nishit Maheta