Children Not Added Properly To DOM Element


#1

When adding child elements to the parent element in the DOM not all of them get added. The console output correctly lists the child elements to add to the parent element. Appears as though the appendChild function in org.w3c.dom.Node in the Kotlin JS standard library isn’t behaving properly. Below is the defined function where the issue occurs:

private fun changeElement(element: ParentHtmlElement, domElement: Element) {
    val newChildren = element.toDomElement().childNodes.asList()

    domElement.clearAttributes()
    domElement.clearChildren()
    element.attributes.forEach { (key, value) -> domElement.setAttribute(key, value) }
    if (element.id.isNotEmpty()) domElement.id = element.id
    if (element.txtContent.isEmpty()) {
        domElement.textContent = null
    } else {
        domElement.textContent = element.txtContent
    }
    // TODO: Remove the line below.
    newChildren.forEach { println("Item: ${it.textContent}") }<img src="/uploads/kotlinlang/original/2X/4/435087ac2ad1e26c9a1a0a15d2148dc4324bd537.png" width="657" height="410">
    newChildren.forEach { domElement.appendChild(it) }
}

Is there a workaround for adding child elements to a parent element? Below is a screenshot of the results:


#2

Turns out that using the replaceWith function instead of the appendChild function fixes the issue. Below is the revised code sample:

fun Document.updateElementById(init: () -> Tag) {
    val tag = init()
    val domElement = document.getElementById(tag.id)

    domElement?.replaceWith(tag.toDomElement())
}

Not an ideal solution since more resources are required to create a new DOM Element that replaces the existing one.


#3

I have no idea what is a ParentHtmlElement and how you use the provided function. Without self-contained example it’s hard to tell what goes wrong. One thing I can tell definitely is that appendChild is defined in the following way:

public external abstract class Node : EventTarget {
    // some code skipped
    fun appendChild(node: Node): Node

Withot body! This means, it’s not Kotlin implementation, it’s just declaration of existing JavaScript DOM API. You can check yourself by just navigating to appendChild function in IDEA. If something goes wrong, please, check that you are using DOM API properly. Documentation can be found on MDN, for example.