Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

173
Views
automatically remove a div with javascript

I have a “noticeboard” that displays upcoming events that are occurring in the community.

Each Event is constructed as follows:

<div class=”image” id=”30-9-21” data-name=”Thursday”>
    <span><img src=”cooking-class.jpg” alt=”cooking class”></span>
    <h4 id=”date”>30/9/2021</h4>
    <h4 id=”day”>Thursday Night</h4>
    <p id=”text”>Come join us for some cooking lessons.</p>
</div>

Once the date is less than Today’s date I would like to create a script that hides that div, so it no longer shows up on the noticeboard.

I have seen a few scripts that remove a by clicking a button as follows:

<button onclick=”remove_click()”>
    Click to remove
</button>

<script type=”text/javascript”>
    function remove_click() {
    var 30-9-21 =
    document.getElementById(“30-9-21”);
    30-9-21.remove();
}
</script>

I would like to automate the process so it happens automatically once the id is less than Today.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You can use the Date.prototype.getTime() feature to compare the current time against the time that the object should be hidden.

If the object still needs to be hidden, you can simply subtract the current time from the time the div should disappear to get the milliseconds the program needs to wait.

// Fetches block
let block = document.getElementById("30-9-21");

// Finds current time
let now = new Date();

// Finds time to hide object
let expire = new Date("9-31-2021");

// If the time to hide the object has already gone by, destroy the div block
if(now.getTime() >= expire.getTime()){
  block.remove();
}else{
  // Otherwise, destroy it when the time to hide the object occurs.
  window.setTimeout(() => {
    block.remove();
  }, expire.getTime() - now.getTime());
}
<div class="image" id="30-9-21" data-name="Thursday">
    <span><img src=”cooking-class.jpg” alt=”cooking class”></span>
    <h4 id="date">30/9/2021</h4>
    <h4 id="day">Thursday Night</h4>
    <p id="text">Come join us for some cooking lessons.</p>
</div>

about 4 years ago · Juan Pablo Isaza Report

0

Since you are not using a database to query your data, then this is what I would suggest.

  1. Place all your class information into an array of object
  2. Run a for loop to loop through each class
  3. Compare if the date for each class has passed today or your requirement
  4. Add classes that pass your requirements to the DOM

The idea I am trying to show is that if you maintain an array of "classes", you will be able to compare the date and append it to the document only if it fulfills the requirement.

You can test it out below. Feel free to add the alt text or any other ids or classes.

let classArray = [
  {
    date: '9-30-2021',
    time: 'Night',
    text: 'Come join us for some cooking lessons',
    image: 'cooking-class.jpg'
  },
  {
    date: '10-4-2021',
    time: 'Night',
    text: 'Come join us for some cooking lessons',
    image: 'cooking-class.jpg'
  },
  {
    date: '10-10-2021',
    time: 'Night',
    text: 'Come join us for some cooking lessons',
    image: 'cooking-class.jpg'
  }
];

let days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

function generateClass(data) {
  let classContainer = document.createElement("div");
  classContainer.className = 'image';
  classContainer.id = data.date;
  let date = new Date(data.date);
  classContainer.setAttribute('data-name', days[date.getDay()])
  classContainer
  classContainer.innerHTML = `
    <span><img src="${data.image}"></span>
    <h4 id="date">${date.getDate()}/${date.getMonth() + 1}/${date.getFullYear()}</h4>
    <h4 id="day">${days[date.getDay()]} ${data.time}</h4>
    <p id="text">${data.text}</p>
  `;
  return classContainer;
}

let today = new Date();
for(let i=0; i < classArray.length; i++) {
  if(new Date(classArray[i].date) > today) {
    document.getElementById('class-list').append(generateClass(classArray[i]));
   }
}
<div id="class-list"></div>

about 4 years ago · Juan Pablo Isaza Report

0

Don't use date in id attribute, use special attribute for this because you may have multiple events with same date (using multiple id with same value is bad practice), so I have used date attribute please check below code.

And if you want to change date format from date-month-year to month/date/year update date format and date divider in htmlDateSettings variable in javascript below.

I have increased one day to event date, if want to hide event which are less than now please remove filteredDate = filteredDate + msInOneDay; in javascript below.

I have used two events with different date.

I have filtered date format because javascript need different date format than yours.

Ok now it will automatically hide events which are expired or less than one day from now.

const htmlDateSettings = {
    "date-format": "d-m-y",
    "date-devider": "-"
}

removeExpiredEvents(); // call function automatically

function removeExpiredEvents() {
    let eventItems = Array.from(document.querySelectorAll('.eventItem'));
    let df = htmlDateSettings['date-format'];
    let dd = htmlDateSettings['date-devider'];
    let msInOneDay = 1000 * 60 * 60 * 24;
    let today = new Date().getTime();

    for(let eventItem of eventItems) {
        let date = eventItem.getAttribute('date');
        if(!date) continue;

        date = date.split(dd);
        let dateFormat = df.split(dd);

        let filteredDate = `${date[dateFormat.indexOf('m')]}/${date[dateFormat.indexOf('d')]}/${date[dateFormat.indexOf('y')]}`;
        filteredDate = new Date(filteredDate).getTime();
        filteredDate = filteredDate + msInOneDay; // increased 1 day in event date
        
        if(today > filteredDate) eventItem.style.display = 'none'; 
    }
}
<div class="image eventItem" date="30-9-21" data-name="Thursday">
    <span><img src="cooking-class.jpg" alt="cooking class"></span>
    <h4 id="date">30/9/2021</h4>
    <h4 id="day">Thursday Night</h4>
    <p id="text">Come join us for some cooking lessons.</p>
</div>

<!-- today event -->
<div class="image eventItem" date="12-10-21" data-name="Thursday">
    <span><img src="cooking-class.jpg" alt="cooking class"></span>
    <h4 id="date">12/10/2021</h4>
    <h4 id="day">Thursday Night</h4>
    <p id="text">Come join us for some cooking lessons.</p>
</div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!