Facebook
Twitter
LinkedIn
Instagram
Whatsapp
Call Now
Quick Inquiry

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

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>

9 0

Write a Comments


* Be the first to Make Comment

GoodFirms Badge
GoodFirms Badge

Fix Your Meeting With Our SEO Consultants in India To Grow Your Business Online