2

Is it possible to append a child back to a position within a <td> element in a table. I have 4 basketballs and when one is dragged to a net after a period of about 800 milliseconds I want to return it to it original position. I can remove the child node (the selected basketball) and I can return it to the table after a time.

The HTML code:

<td id="tdId1" style="width:60px;"><div id="bball1" onclick="ballSelection(this.id)"></div></td>    
<td id="tdId2" style="width:60px;"><div id="bball2" onclick="ballSelection(this.id)"></div></td>
<td id="tdId3" style="width:60px;"><div id="bball3" onclick="ballSelection(this.id)"></div></td>
<td id="tdId4" style="width:60px;"><div id="bball4" onclick="ballSelection(this.id)"></div></td>

The problem is that when I remove it and then append it, It appends to the end of the row <tr> element and not the <td>. It always append to the last position.

Can it be appended to its original place. For example second in the row?

The JavaScript code:

var node = document.getElementById(this.Id);
if (node.parentNode) {
    node.parentNode.removeChild(node);
    var node2 = document.getElementById("tdId2");
    setTimeout(function() {node2.parentNode.appendChild(node); }, 800);
}

I have tried to append to the second just as a starting point.

Any help appreciated.

Nicolas78
  • 5,124
  • 1
  • 23
  • 41
Ger
  • 49
  • 4

2 Answers2

1

You are using the wrong parent to append. You select one of the TDs and then access the parent of that which is the TR and then appending to that. Just save a reference to the parent before removing and then append to that reference

var node = document.getElementById(this.Id);
if (node.parentNode) {
   var parent = node.parentNode;
   parent.removeChild(node);
   setTimeout(function() {parent.appendChild(node); }, 800);
}
Patrick Evans
  • 41,991
  • 6
  • 74
  • 87
0

append by definition appends to the end of the collection. To insert into a different position, you need to get a hold on the element you want to insert after, then user insertAfter. See this question: Javascript Append Child AFTER Element

Also, if you do more of this, you might want to consider having a look at jQuery

Community
  • 1
  • 1
Nicolas78
  • 5,124
  • 1
  • 23
  • 41