What is the best way to completely eliminate a div from a webpage

I've created a new div element using jQuery:

$(document.body).append('<div id="test"></div>');

Then, I display a success message and remove the div after 10 seconds:

$('test').html('SUCCESS!');
setTimeout(function(){
  $('#test').remove();
}, 10000);

After that, I check if the div removal is complete and log a message to the console:

$(window).on('scroll', function () {
    if($('#test').length === 0){
      console.log('DIV removed!');
    } else {
      console.log('DIV not removed!!!')
    }
}

Unfortunately, when I scroll up or down, the message "DIV not removed!!!" is displayed.

Can anyone explain why my div is not being removed?

Answer №1

Upon adding your "check" to the DOM, you immediately execute a check on it. The actual removal of the "check" occurs ten seconds later.

To illustrate the difference in code placement, I have made adjustments to the example. Feel free to click run and see the results.

I have also reduced the time from 10 seconds to 2 seconds for a quicker demo.

In essence, make sure to run the code intended to execute after the removal right after the removal line itself.

$(document.body).append('<div id="test"></div>');

$('#test').html('SUCCESS!');
setTimeout(function(){
  $('#test').remove();
  
  // Executed LATER
  if($('#test').length === 0){
    console.log('[LATER] DIV removed!');
  } else {
    console.log('[LATER] DIV not removed!!!')
  }
}, 2000);

// Executed immediately, Before setTimeout has finished
if($('#test').length === 0){
  console.log('[IMMEDIATE] DIV removed!');
} else {
  console.log('[IMMEDIATE] DIV not removed!!!')
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Answer №2

// When the page loads
$(function(){
  // Set the body height to 1000px to support scroll events
  $('body').css('height','1000px');
  
  // Append a new div with id "test" to the body
  $(document.body).append('<div id="test"></div>');
  $('#test').html('SUCCESS!');
  
  // Remove the div after 2 seconds
  setTimeout(function(){
    $('#test').remove();
  }, 2000);
  
  // Scroll event listener
  $(window).on('scroll', function () {
      if($('#test').length === 0){
        console.log('DIV removed!');
      } else {
        console.log('DIV not removed!!!')
      }
  });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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

The art of revealing and concealing code blocks in AngularJS

I am currently working on a task in my AngularJS project. The requirement is that when both point directives within the md-autocomplete code are filled, the results directive should be displayed immediately without the need for any button. Additionally, if ...

Changing the text in a Bootstrap tool-tip

Currently encountering an issue where I am attempting to modify the text displayed in a tooltip, but it appears that the change is not taking effect. Instead, upon hovering over, you will see the text "your new title." My goal is simply to alter the text w ...

Tips for personalizing your Magento 2 theme

As someone new to Magento 2 and front-end development with a basic knowledge of HTML and CSS, I am eager to customize the blank theme in Magento 2 to gain a deeper understanding of how things work. However, despite reading through the documentation, I am u ...

A method to verify the presence of a specific element within a list using JavaScript

I'm trying to validate if the list retrieved from the application contains the expected element. Can you please review my code and let me know where I might be making a mistake? this.verifyOptionsInDropdown = async function(){ var optionList = a ...

What is the best way to transfer information from JavaScript to a JSON database using the fetch API?

Within the userDB.json file, it appears as follows; [{ "username": "john", "xp": 5 }, { "username": "jane", "xp": 0 } ] Inside the app.js file ; async function getUsers() { le ...

PHPBB authentication system

After experimenting with the script based on the guidance I received from you all, I've encountered another issue. When I click 'login' on the login form, it displays this message: The page isn't redirecting properly. Firefox has detect ...

Expanding the jQuery AutoComplete Plugin: A Guide to Implementing the bind keyup Event

Currently, I am utilizing a plugin that enhances the features of the jQuery AutoComplete UI Plugin: https://github.com/experteer/autocompleteTrigger/blob/master/jquery-ui.autocompleteTrigger.js Within the select method, an event and ui variable are passe ...

Tips for invoking an asynchronous function within an if condition?

When trying to maintain variables in the background.js of a Chrome extension, I encountered difficulties that require me to reinitialize some global variables. Here is the code snippet (view fiddle) I am using to demonstrate the issue: var temp = null; ...

Exploring the ins and outs of console interactions in JavaScript

I have come across a problem on Hacker Rank that seems quite simple. The task involves working with N strings, each of which has a length no more than 20 characters. Additionally, there are Q queries where you are provided a string and asked to determine ...

Switch out an item within a list of objects with a different item

I have a variable called this.rows that contains a collection of items. There is a real-time item being received from the server, which matches one of the items in the this.rows object collection. How can I replace an item with new values? Below is an ex ...

Angular ng-if directive contains a specific class

I am trying to create a directive that will only be active when an element has a specific class. I have tried the following code: <feedback-analytics ng-if="$('#analyticTab').hasClass('active')"></feedback-analytics> Unfor ...

I am looking for an HTML solution that allows me to neatly stack photos of different sizes in two columns, always prioritizing the column with more empty space

Is there an easy method to populate two columns, each with a width of 50%, with photos in a way that the next photo is always added to the column with more available space? The photos come in different sizes but should be able to fit within the width of t ...

Text alongside a perfectly aligned image

I'm facing a dilemma. I've been striving to replicate the layout of my training website blocks to look like this: http://prntscr.com/4cd4gm. However, aligning text and paragraphs has become an obstacle for me. Despite succeeding in aligning pictu ...

List arranged in order with a hyperlink in the center and an image positioned on the right side

I am trying to create an ordered list with a link to an article in the middle and a small png image file positioned directly to the right of it. For reference, here is an image depicting the exact type of list that I am aiming to achieve: https://i.stack. ...

Implement the usage of plainToClass within the constructor function

I have a dilemma with my constructor that assigns properties to the instance: class BaseModel { constructor (args = {}) { for (let key in args) { this[key] = args[key] } } } class User extends BaseModel { name: str ...

Tips on deleting specific elements from an array by utilizing the splice method

Here are the details of my first array: [ { members: [ '60ee9148104cc81bec3b97ab' ] } ] And this is the second array: [{"_id": "60ee9148104cc81bec3b97ab","username": "user1", "email": "< ...

Struggling with implementing private npm modules using require() and import

Trying to import a private npm module hosted in sinopia, I can see it available in the sinopia folder structure. I successfully installed the module via "npm install --save", and it seems to pick it up from the local registry. However, when attempting to ...

Using multiple selectors in JQuery and Javascript

I have a challenge where I need to execute different actions for specific divs. Here is the code snippet I currently have: $("#pending-cancel-1, #pending-cancel-2").click(function(){ Do something special for pending-cancel-1 and pending-cancel-2... }) ...

Implementing a hamburger menu and social media sharing buttons on websites

Currently working on my personal website and delving into the world of Web Development, I have some inquiries for seasoned developers. My first query revolves around incorporating a hamburger menu onto my site for easy navigation to other pages. After att ...

error 404 when sending a xhr request in node and react js

I am currently developing a basic login page in React that needs to connect to a database through an AJAX call to a Node.js file. Here is the Node.js code I have implemented: var express=require('express'); var app=express(); var db=require(&ap ...