insertAdjacentHTML then select with dom selector

428 Views Asked by At

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.

4

There are 4 best solutions below

0
On BEST ANSWER

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>

0
On

You said "I want to insert some unknown HTML (contentToInsert) and remove it later at some point"

I wouldn't use insertAdjacentHTML at all. Here's how you can achieve it:

let myDiv = document.getElementById('myDiv');
let contentToInsert = "<h1>Some html content</h1>";

myDiv.innerHTML = contentToInsert;

This will insert your content into your div. And you can remove it with:

myDiv.innerHTML = "";
0
On

in one of the cases...

const 
  divElm   = document.querySelector('#div-elm')
, Insert_1 = '<span>inserted content 1 </span>'
, Insert_2 = '<span>inserted content 2 </span>'
  ;

divElm.insertAdjacentHTML('afterbegin', Insert_1);
const ref_1 = divElm.firstChild;

divElm.insertAdjacentHTML('afterbegin', Insert_2);
const ref_2 = divElm.firstChild;

ref_1.classList.add('RED')
ref_2.classList.add('BLU')

console.log( '', ref_1, `\n`, ref_2 )
.RED { color: red; }
.BLU { color: blue; }
<div id="div-elm">
  blah blah bla..
</div>

0
On

many amazing people already answered your question but here's a workaround, if you're only Adding this specific html using js and other content is preadded in html it's always gonna be the first child as you're using afterbegin or else you can do it like others gave you examples.

Sorry can't comment not enough reputation and recently joined