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

.
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e4c0a1-44e95.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e4c0a1-44e95.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?