perform an action if any division element is void of content

Currently, I have a statement that checks if any of the Divs with the ID #Drop are empty. If one is found to be empty, an alert is shown. However, there seems to be an issue where the statement stops working when any div contains content.

What I am trying to achieve is for an alert to display if ANY div is empty. There are 4 Divs in total, and the alert message should appear whenever there is an empty div irrespective of whether other divs contain content.

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")// ...
    }
});

Answer №1

Utilize jQuery's :empty selector to select elements with no children. For more information, visit the :empty selector page.

Description: This selector targets elements that do not have any children (including text nodes).

View a live demonstration here.

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

Alternatively, as mentioned in my comment and @A. Wolff's answer comment, here is the second option:

DEMO

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

Answer №2

$("#run").click(function(){
    if ($("[id^='Drop']").is(":empty")){
        alert("The drop containers are 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>

Answer №3

If you want to give this a shot, you could consider trying something along these lines

$('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>

Answer №4

Give this a shot:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the potential of TypeScript with native dynamic ES2020 modules, all without the need for Node.js, while also enhancing

I have a TypeScript application that utilizes es16 modules, with most being statically imported. I am now looking to incorporate a (validator) module that is only imported in debug mode. Everything seems to be functioning properly, but I am struggling to f ...

Displaying a div after a successful form submission using Jquery

I created two popup windows. One is used to ask the user whether they want to submit the form, and if they click 'yes', the form is submitted. The issue I encountered is that the other popup window should be shown after the form is successfully s ...

What could be the reason for my jQuery focusout (or blur) event failing to trigger?

On the jsfiddle link provided, the HTML code at the end section looks like this: <input type="text" id="BLAboxPaymentAmount" value="2"> </br> <input type="text" id="BLAboxSection5Total" value="3"> Below that is the jQuery code snippet: ...

Counting each item with jQuery and assigning them numbers 02, 03, 04, etc., with the exception of the first item which will display as "Up Next

I'm still learning jQuery and here's the code I've put together after researching on stackoverflow and other platforms: var counter = 1; $('.next-page .nav-item').each(function () { if ($(this, ':gt(0)')) { $(this ...

Retrieve the header tag from API using Nuxt

I am trying to dynamically set OG:Tags using an API head() { this.$axios .get(`............`) .then((response) => { this.og_title = response.data.message.course.course_name; this.og_description = response.data.message.course.description; ...

When switching from JavaScript to jQuery, the button values become invisible

Currently, I have a functional app that can dynamically change the values of buttons based on user input. The current implementation is in vanilla JavaScript within the script.js file. However, I am looking to enhance the functionality and user experience ...

Unable to run JavaScript file fetched from cache API

For a web application built using pure vanilla JavaScript without utilizing service workers, I am looking to cache a JavaScript file hosted on an AWS S3 file server explicitly. The script below will be embedded in the index.html file of the application (UR ...

Perform an AJAX request to an encrypted URL with an unverified certificate

I'm experiencing an issue with my site that makes AJAX JSONP calls to a secured (SSL) web server. Everything works smoothly when using an unsecured (HTTP) web server, but once I switch to the SSL version, the call never returns. After checking with Fi ...

The nodes.attr() function is invalid within the D3 Force Layout Tick Fn

I'm currently experimenting with the D3 Force Layout, and I've hit a roadblock when it comes to adding elements and restarting the calculation. Every time I try, I keep encountering this error: Uncaught TypeError: network.nodes.attr is not a fun ...

Avoiding unnecessary re-renders in your application by utilizing the useRef hook when working with

To prevent the component from re-rendering every time the input value changes, I am trying to implement useRef instead of useState. With useState, the entire component re-renders with each key press. This is the usual approach, but it causes the entire co ...

What is the best way to retrieve the IDs of selected items in jQuery selectables?

I have a straightforward question that I've been struggling to find an answer to. When using jQuery selectables, I want to retrieve the ID of the selected list item when it's clicked. Here is an example of my list: <ol id="selectable"> ...

Utilizing JavaScript within the Spring MVC form tag

Can you please assist me with the following question? I am currently working on a project using JSP, where we are utilizing Spring form tags. My issue involves creating two radio buttons that, when clicked, will display different options and pass the sele ...

Tips on navigating an array to conceal specific items

In my HTML form, there is a functionality where users can click on a plus sign to reveal a list of items, and clicking on a minus sign will hide those items. The code structure is as follows: <div repeat.for="categoryGrouping of categoryDepartm ...

A guide on how to perform a PUT or DELETE operation for Azure Table Storage using Node.js

I've been faced with a challenge in my project where I aim to create basic CRUD functionality for Azure Table Storage. However, I'm encountering difficulties in generating a valid SharedKeyLite signature. While I can successfully generate valid ...

A guide on how to efficiently retrieve all images stored in a specific directory

I attempted to showcase all the images from a single directory using jQuery, but unfortunately it is not functioning as expected. My folder setup includes an 'images' folder and a 'js' folder. I followed this question on Stack Overflow ...

Troubleshooting the issue with the default dropdown select in AngularJS

var jsonData ='[ {"type":"product", "id":1,"label":"Color", "placeholder":"Select Jean Color", "description":"", "defaultValue":"Brown", "choices":[{ "text":"Denim", "price":"$0.00", "isSel ...

The embedded CartoDB image header is set to have a style of "display:none"

I'm currently working on a CartoDB map showcasing my readers' summer fishing photos. Each row in the table has an image url, which I've placed at the top of the infowindow display list. I've enabled it and set the image window type to ...

Error: Unable to modify a property that is marked as read-only on object '#<Object>' in Redux Toolkit slice for Firebase Storage in React Native

Hey there! I've been working on setting my downloadUrl after uploading to firebase storage using Redux Toolkit, but I'm facing some challenges. While I have a workaround, I'd prefer to do it the right way. Unfortunately, I can't seem to ...

Ensuring Filesize Verification Prior to Upload on Internet Explorer Using Javascript

Can JavaScript be used to verify a file's size before it is uploaded to the server at the client side? This application is developed using EXTJS and Java and is limited to Internet Explorer 7 on Windows XP machines. ActiveX cannot be used. The workf ...

Creating a function to limit the display value of Material UI Autocomplete similar to Material UI Multiple Select's renderValue

Incorporating Material UI Features Utilizing the Material UI Multiple Select, you have the ability to truncate the displayed value after selection instead of wrapping onto another line by setting the renderValue to .join for the selected options, enabling ...