How can I remove an HTML element after let's say 2 days.
For example I have a
<div> Hello there </div>.
I was looking JS .hide and .remove functions but not sure if using JS is the best approach?
Thank you.
How can I remove an HTML element after let's say 2 days.
For example I have a
<div> Hello there </div>.
I was looking JS .hide and .remove functions but not sure if using JS is the best approach?
Thank you.
The best way to solve this issue without any server side script is using javascript.
Set a single unique ID for the given div and modify the following code as needed.
// Date(year, month, day, hours, minutes, seconds, milliseconds);
var expire_date_block_1 = new Date(2018, 1, 28, 0, 0, 0, 0);
var expire_date_block_2 = new Date(2018, 4, 28, 0, 0, 0, 0);
if (expire_date_block_1 <= Date.now()) {
document.getElementById("div-hide-example-1").style.display = "none";
}
if (expire_date_block_2 <= Date.now()) {
document.getElementById("div-hide-example-2").style.display = "none";
}
<div id="div-hide-example-1"> Expired Block </div>
<div id="div-hide-example-2"> Not Expired Block </div>
Note that the expire date is in the future.
Just did an example on a way to do it. You should adapt and change the code as needed.
As a side note, @Rounin mentioned, you could also do it on css with some preconditions: keep the page open and don't reload it.
You should be able to do this using Javascript timeouts:
setTimeout(() => {
const elem = document.getElementById("div-1");
elem.parentNode.removeChild(elem);
}, 2000);
<div id="div-1">
<p>Div "div-1" will be removed in 2 seconds...</p>
</div>
EDIT: If you are not using ES6 syntax, your Javascript code snippet would look like:
setTimeout(function() {
var elem = document.getElementById("div-1");
elem.parentNode.removeChild(elem);
}, 2000);
For your goal better to use server side, but this working on the browser, if user don't use different browsers
var el = document.getElementById('del');
var deleteTime = localStorage.getItem('timeToDel');
var curDate = new Date().getTime();
if (!deleteTime) {
deleteTime = curDate + 172800000; //2days by default
localStorage.setItem('timeToDel', deleteTime);
}
var timeToDelete = deleteTime - new Date().getTime();
if (timeToDelete < 0) {
timeToDelete = 0;
}
setTimeout(function() {
el.parentNode.removeChild(el);
}, timeToDelete);
<div id="del"> Hello there </div>