<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);
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.