JavaScript/Restructure DOM

Besides adding and removing nodes, a common activity on trees is the rearranging of nodes respectively of sub-trees. In some of the previous examples, we have seen that  inserts a node as the last child of a parent node. Of course, this is not delimited to the case that the child is currently created. The same operation is possible for an existing node. Hence it is an appropriate function to perform rearrangements.

Example page
We use the following example HTML page to demonstrate the possibilities.

Move an element to the end of siblings
We identify two elements and move them to the end of another node. This other node is not necessarily the old parent. But after the movement, it becomes the new parent.

As you see, the 'Ice creme' is moved to the end (temporarily) of its product group. After that, the 'cakes', which were a child of the second product group, were moved to the end of the first product group.

Move an element before a sibling
You can move an element to any position within a group of siblings. ('Siblings' are nodes with a common parent node.) First, you must locate the parent. Next, you locate the child, which shall become the new successor of the element. When both nodes are known, the function  inserts the element to this position.

As an example, we move the 'Cakes' to the first place of the first product group.

Here, the 'Cakes' become the first element of the first product group. With the same commands you can move them to any position in the sequence of siblings. Just locate the sibling that shall be his new successor instead of 'li_11'.

Attributes
The sequence of attributes within an element is in no way relevant. Hence, there is no need and no function to rearrange them. When a DOM gets serialized, programs may do it in different ways (original sequence, alphabetically, ...).

Exercises

 * ... are available on another page (click here).