Monitor element attached in DOM or not

Use an IntersectionObserver to see if a given element, created with JS, is attached/detached from the DOM.

by David Iglesias

HTML

<div id="log" class="log"></div>

<button id="attach">Attach</button>
<button id="detach">Detach</button>

<div id="target">
  <!-- The place where we'll attach/detach the `el` created with JS -->
</div>

CSS

/* All of this is just optional eye-candy. */

.fancy {
  border: 2px solid red;
  color: #900;
  font-family: sans-serif;
  margin: 10px 0;
  padding: 10px;
}

.log {
  background: #eee;
  border: 1px solid #999;
  border-radius: 3px;
  color: #999;
  height: 100px;
  margin: 10px 0;
  padding: 10px;
  overflow: auto;
}

.log pre { margin: 0; padding: 0; }

JavaScript

// This is the element that we create with JS.
let el = document.createElement('div');
el.innerText = 'Created with JS!';
el.classList.add('fancy');

// Use an IntersectionObserver to detect if `el` is in the DOM or not.
let observer = new IntersectionObserver((entries, observer) => {
  if (el.isConnected) {
  	showInLog(`[${Date.now()}] el: ATTACHED to the DOM`);
  } else {
  	showInLog(`[${Date.now()}] el: NOT attached to the DOM`);
  }
  // If we only care about the first el.isConnected, we can use
  // the incoming `observer` to detach all this and clean it up
  // after we're done.
});
observer.observe(el);

// Buttons, UI, eye candy, and other less relevant code...
attach.addEventListener('click', (e) => {
  target.appendChild(el);
  setAttachDisabled(true);
});

detach.addEventListener('click', (e) => {
  target.replaceChildren();
  setAttachDisabled(false);
});

setAttachDisabled(false);

function setAttachDisabled(value) {
  attach.disabled = value;
  detach.disabled = !value;
}

function showInLog(txt) {
  let entry = document.createElement('pre');
  entry.innerText = txt;
  log.prepend(entry);
}