Удаление insertAdjacentHTML
const modal = document.createElement('div')
function createModal (src){
modal.classList.add('modalBg');
modal.insertAdjacentHTML('afterbegin',
`<div class="modalWr">
<div id="close-modal" onclick="closeModal()">
<p class="closeModalX">X</p>
</div>
<div class="modalImgBlock">
<img src="${src}" alt="" id="imgModal">
<div class="modalBlockControl">
<button>btn1</button> <button>btn2</button>
</div>
</div>
</div>`
)
document.body.append(modal);
}
Создал таким образом "модальное окно", а когда пытаюсь закрыть и открыть с другим изображением эти два блока перекрывают друг-друга. Каким образом можно полностью удалить окно? Использую remove().
Ответы (2 шт):
Автор решения: Давид Манжула
→ Ссылка
А если вот так?
const modal = document.createElement('div');
modal.classList.add('modalBg');
modal.innerHTML = `
<div class="modalWr">
<div id="close-modal" onclick="closeModal()">
<p class="closeModalX">X</p>
</div>
<div class="modalImgBlock">
<img src="" alt="" id="imgModal">
<div class="modalBlockControl">
<button>btn1</button> <button>btn2</button>
</div>
</div>
</div>
`;
function showModal (src){
document.getElementById("imgModal").src = src;
modal.classList.add('modal-show');
}
function closeModal (){
modal.classList.remove('modal-show');
}
Автор решения: Вуьшта
→ Ссылка
function createModal (src){
const modal = document.createElement('div')
modal.classList.add('modalBg');
modal.insertAdjacentHTML('afterbegin',
`<div class="modalWr">
<div id="close-modal" onclick="closeModal()">
<p class="closeModalX">X</p>
</div>
<div class="modalImgBlock">
<img src="${src}" alt="" id="imgModal">
<div class="modalBlockControl">
<button>btn1</button> <button>btn2</button>
</div>
</div>
</div>`
)
document.body.append(modal);
}
Нужно просто вызывать метод removeChild()
Пример:
function closeModal() {
modal.removeChild(document.querySelector('.modalWr'));
modal.remove();
}