Meghana M
Meghana M

Reputation: 535

Does element.appendChild(node) applies properties of parent node to child node?

I am new to HTML and JS. Need to create dynamic expand-collapse list. var parentId = document.getElementById("ABCD") parentId.setAttribute("data-toggle","collapse") parentId.setAttribute("data-target","#collapse1") var tag = document.createElement("ul"); tag.setAttribute("id","collapse1") tag.appendChild(document.createTextNode("PQR")) parentId.appendChild(tag)

Trying for list as- ABCD PQR

So in this case, when i am clicking on ABCD, PQR gets expanded/collapsed. But the problem is on clicking on PQR, it gets collapsed again. So does the properties of parent gets applied to child node also?

Upvotes: 0

Views: 117

Answers (1)

dave.mcalpine
dave.mcalpine

Reputation: 407

it's not that it gets properties of it's parent, this has to do with how events handled, specifically event bubbling. When you click a child element, a click event if fired for all parent elements of what you clicked on

to cancel the event from bubbling when you click the appended elements you need to event.stopPropagation() inside of a click handler for the new elements

after you append them do the following

// tag.appendchild code goes here, then do the following

document.querySelector("#collapse1").onclick=function(event){
    event.stopPropagation();
}

also, i should mention all this would be 10 times easier with jQuery

Upvotes: 1

Related Questions