[Javascript] Changing an Objects ID and Name

Nick Fitzsimons nick at nickfitz.co.uk
Thu Sep 7 05:54:18 CDT 2006


On 7 Sep 2006, at 11:33, Paul Novitski wrote:

> At 9/6/2006 11:07 PM, Jonathan Buchanan wrote:
>> On 9/7/06, Terry Riegel <riegel at clearimageonline.com> wrote:
>>>
>>> I modified it slightly to include the type of node being swapped.
>>>
>>> function swapNodes(n1, n2, k)
>>> {
>>>     var placeHolder = document.createElement(k);
>>>     n1.parentNode.replaceChild(placeHolder, n1);
>>>     n2.parentNode.replaceChild(n1, n2);
>>>     placeHolder.parentNode.replaceChild(n2, placeHolder);
>>> }
>>>
>>> Is there some type of cleanup needed to remove the temporary node
>>> (placeHolder)? Or is it local to the function and gets removed
>>> automatically?
>>
>> As placeHolder is declared using "var", it's local to the function.
>> When the function returns, placeHolder is not attached to the  
>> document
>> any more and there are no other references to it hanging around,  
>> so it
>> should get removed automatically.
>
>
> Jonathan, I suspect you're wrong on this point.  While I agree that  
> the variable 'placeHolder' is local to the function 'swapNodes()'  
> and will be cleared when the function terminates, surely when you  
> invoke the DOM method createElement() you're creating a new element  
> IN THE DOM which has got to be about as global as you can get in a  
> script running in the context of the Document Object Model.

> Am I wrong about this?  Does the createElement() method return a  
> node object that isn't actually part of the DOM and doesn't persist  
> when the calling function returns?
>

If you examine a node returned by createElement you will see that it  
has no parentNode; it isn't part of the DOM tree until it is  
explicitly inserted into the tree. In this case it is inserted and  
then removed, so the only remaining reference to it is in the local  
variable. Therefore it should be available for garbage collection  
when the function terminates.

Cheers,

Nick.
-- 
Nick Fitzsimons
http://www.nickfitz.co.uk/






More information about the Javascript mailing list