I want to insert some unknown HTML (contentToInsert) and remove it later at some point.
If I use insertAdjacentHTML, I cannot later say
myDiv.insertAdjacentHTML('afterbegin', contentToInsert); myDiv.querySelector('contentToInsert') //cannot work of course
because this does not have id or classname.
I cannot wrap it like this (so I have reference to it later):
var content = document.createElement('div'); content.classList.add('my-content-wrap') content.innerHTML = contentToInsert; myDiv.insertAdjacentHTML('afterbegin', adContent);//it can be any allowed position, not just afterbegin
Basically I want to remove it later at some point but dont know how to select it. I dont know the position in which this is going to be instered.
Advertisement
Answer
Since insertAdjacentHTML
only accepts a string you can
- Define your content as a string
- Use a template/string to add it
- Add that string to
myDiv
.
Then you can target myDiv
again with a selector pointed at that element with the my-content-wrap
class, and remove it from the DOM.
const myDiv = document.querySelector('#myDiv'); const content = 'Disappears after two seconds'; const html = `<div class="my-content-wrap">${content}</div>`; myDiv.insertAdjacentHTML('afterbegin', html); const pickup = myDiv.querySelector('.my-content-wrap'); setTimeout(() => pickup.remove(), 2000);
<div id="myDiv">Original content</div>