How does JavaScript detect that it has been inserted into the real dom, and calculate the width of the li after creating a li, using createElement

js creates a li, through createElement to calculate the width of the li, but before inserting the page, the calculated width is 0. After inserting the page, the true width of the li can be calculated


class Tab{
    constructor(){
        const tab = document.createElement("ul")
        const li = document.createElement("li")
        tab.appendChild(li)
        li.textContent = "test"
        // 1li(li.offsetWidth)0
        // tabdom li.offsetWidth
        return tab
    }
}

const tab = new Tab()
const root = document.getElementById("root")
root.appendChild(tab)
// 2 lioffsetWidth 0
// li render
Apr.01,2021

because the various style attributes are not applied before insertion, the browser does not know how your content should be rendered. After
is inserted into the document, it is rendered by the browser and the properties related to the box model are calculated.


from your code, you can't get the width of li in the constructor, because in the constructor you only insert li into ul and ul is not inserted into DOM, so li is not inserted into DOM, so you can't get it, consider changing your way of thinking to achieve your needs.


looks like you need MutationObserver , which can listen for changes in DOM structure and call functions to handle it.


there seems to be a listening event called DOMNodeInserted that can be hung on li , and then, when inserted, you can get

.
Menu