Mounir said:
I wrote :
Err... in Paul's reply (xhtmI file) I think I got the answer... The
assignment behaves like a DOM child moving (i.e. appendChild()). Right
I think the issue is that DOM objects are host objects, you can't
presume their behaviour will be consistent with ECMAScript native or
built-in objects.
Consider:
var objA = new Object();
objA.firstChild = new Object();
var objB = new Object();
objB.firstChild = objA.firstChild;
Outcome: objA.firstChild and objB.firstChild reference the same object.
Now consider something similar in DOM:
<div id="divA><div id="divC"></div></div>
<div id="divB"><div id="divD"></div></div>
<script type="text/javascript">
var divA = document.getElementById('divA');
var divB = document.getElementById('divB');
divB.firstChild = divA.firstChild;
</script>
Outcome: ?
In a pure ECMAScript context, divB.firstChild and divA.firstChild
should both reference divC, the firstChild of divA. However, since a
DOM element can only have one parent, we are left to guess whether[1]:
1. divC replaces divD
2. divD is moved down the DOM tree to make room for divC
3. an error.
If the intention was that divC is inserted as divB's first child, then:
divB.insertBefore(divA.firstChild, divB.firstChild);
is specified in the W3C DOM HTML spec as doing exactly that, no
guesswork. If we'd wanted divC to replace divB's firstChild:
divB.replaceChild(divA.firstChild, divB.firstChild);
The lesson is that where you want a specific DOM behaviour, use DOM
methods to achieve it. That principle can be applied to any host
object - use the host provided methods to manipulate them.
1. Determining the correct behaviour assumes whoever is reading the
code knows that DOM objects/elements are involved, so naming
conventions become very important. Using DOM methods makes it pretty
clear that DOM objects are being manipulated (though if silliness was
the order of the day, someone may have created their own native
ECMAScript objects and methods with the same names as well known host
objects/methods).