I have a function called validateForm() which checks for me form input. If the input is not as it should be (each field filled) alert message should appear and should be removed after 3 seconds and it does, but each time I call this function this element is created in DOM. How can I improve that code? What I want to get is div with alert message as below, but not created in the DOM each time the function is called, but once.
static validateForm() {
const title = document.querySelector('#title').value;
const author = document.querySelector('#author').value;
const isbn = document.querySelector('#isbn').value;
if (title === '' || author === '' || isbn === '') {
const div = document.createElement('div');
div.className = 'alert alert-dismissible alert-danger';
const message = document.createTextNode('Please fill all fields before adding.');
div.appendChild(message);
const bookForm = document.querySelector('#book-form');
bookForm.parentNode.insertBefore(div, bookForm);
setTimeout(() => {
div.classList.add('d-none');
}, 3000);
return false;
}
return true;
}
applenChild, the related action isremoveChild