I am trying to drag and drop an image from parent A, which has several children, to parent B, which is initially empty. I can specify element.parent = document.getElementById(‘foo’), but the document doesn’t naturally flow as if I had placed the element under foo originally.
I’m presently working around this behavior by having JavaScript style the parent to act as if it contained the child and the child to act as if it were contained in the parent, but I would like to know if there’s a better way to have the document updated to look as if the child were placed under the target parent instead of the origin parent.
You are not moving an item in the DOM correctly – when you do move it correctly the display will update automtically.
You can’t just set the
.parentproperty. First off,.parentisn’t even a property on the DOM element (it’s.parentNode). Second, it isn’t a property you can directly set (per the DOM spec, it is a read-only property). Instead, you need to do it like this:This will remove it from the DOM location it’s currently in and append it as the last child of a new parent node. If you want to place it as a specific child relative to the existing children (e.g. as the 3rd child node or the 1st child node), you can use
.insertBefore()instead of.appendChild().If wanted to copy the node to a new location rather than move an existing node, you would first have to make a copy of the node (either making it from scratch or using
.cloneNode()and then insert the copy into the DOM in the same manner.