I just figured, that ParentNode.replaceChildren() won't work in older browsers, for example chrome. How can I re-write it basically?
ModalBody.replaceChildren(loader);
I just figured, that ParentNode.replaceChildren() won't work in older browsers, for example chrome. How can I re-write it basically?
ModalBody.replaceChildren(loader);
Remove children of ModalBody
const parent = document.getElementById("parent");
parent.innerHTML = '';
And then add the loader
parent.innerHTML = loader
const button = document.querySelector("button")
button.onclick = () => {
// Remove all children of the first, ModalBody
const first = document.getElementById("first")
first.innerHTML = ""
// Add loader
const second = document.getElementById("second")
first.innerHTML = second.innerHTML // loader
}
<div id="first">
<p>A</p>
<p>B</p>
<p>C</p>
<p>D</p>
<p>E</p>
<p>F</p>
<p>G</p>
</div>
<div id="second">
<p>Loader</p>
</div>
<button>Replace</button>
Depends how far back you want to support
function my_replaceChildren(el, nodes) {
if (el.replaceChildren)
return el.replaceChildren(...nodes); // supported Chrome 86+
el.innerHTML = "";
el.append( ...nodes);
}
https://developer.mozilla.org/en-US/docs/Web/API/Element/append
You can remove all children from the element and append the new ones:
function replaceChildren(el, ...children){
el.textContent = '';
for(let child of children){
el.appendChild(child);
}
}
If you are not using a transpiler you will need to make this code compatible with browsers you need to support:
function replaceChildren(el){
var children = Array.prototype.slice.call(arguments, 1);
el.textContent = '';
for(var i = 0; i< children.length; i++){
el.appendChild(children[i]);
}
}
You can take a look at caniuse for browser support data.
I don't why, but this worked:
ModalBody.insertAdjacentHTML('afterbegin', loader.outerHTML);
Basically here is what I have connected to loader:
var loader = document.createElement('div');
loader.classList.add('loader');
loader.classList.add('is-loading');
loader.classList.add('mt-5');
So, when I tried this
ModalBody.insertAdjacentHTML('afterbegin', loader);
instead of getting the moving circle as a sign that content is being loaded, I got [object HTMLDivElement] in my modal instead, which after a couple of seconds was replaced by the right content. So somehow .outerHTML on loader fixed it. I am still new to all this. Maybe someone can explan why it works this way?