javascriptinsertadjacenthtml

insertAdjacentHTML then select with dom selector


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.


Solution

  • Since insertAdjacentHTML only accepts a string you can

    1. Define your content as a string
    2. Use a template/string to add it
    3. 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>