Advertisement

TrimwebsolutionsTrimwebsolutions

Problem and Solutions

How to wait for appendChild() to update and style the DOM, before trying to measure the new element's width in javascript ?

By M.K. Verma · 3 May 2022

How to wait for appendChild() to update and style the DOM, before trying to measure the new element's width in javascript ?

it can done with MutationObserver.
doesn't this method solve your problem?

 

const div = document.querySelector("div");
const span = document.querySelector("span");

const observer = new MutationObserver(function () {
  console.log("new width", size());
});

observer.observe(div, { subtree: true, childList: true });

function addElem() {
  setTimeout(() => {
    const newSpan = document.createElement("span");
    newSpan.innerHTML = "second";
    div.appendChild(newSpan);
    console.log("element added");
  }, 3000);
}

function size() {
  return div.getBoundingClientRect().width;
}

console.log("old width", size());
addElem();
div {
  display: inline-block;
  border: 1px dashed;
}
span {
  background: gold;
}
<div>
  <span>one</span>
</div>