JSFiddle - React, Tailwind, and code Playground
HTML
<button id="target">Click me!</button>
<div id="area"></div>
CSS
.square {
width: 100px;
height: 100px;
background: red;
display: inline-block;
margin: 5px;
}
JavaScript
const target = document.getElementById('target');
const area = document.getElementById('area');
target.addEventListener('click', e => {
const div = document.createElement('div');
div.classList.add('square');
area.appendChild(div);
});
const mo = new MutationObserver((...args) => {
if (area.children.length > 4) {
const iframe = document.createElement('iframe');
iframe.setAttribute('width', 500);
iframe.setAttribute('height', 360);
iframe.src = 'https://www.youtube.com/embed/dQw4w9WgXcQ?autoplay=1';
iframe.setAttribute('frameborder', 0);
iframe.setAttribute('allow', 'autoplay; encrypted-media');
iframe.setAttribute('allowfullscreen', true);
area.innerHTML = '';
area.appendChild(iframe);
}
});
mo.observe(area, {
childList: true
});