I just finished my first JavaScript object, and I’m pretty pleased with myself. What this does is make things much easier to move or copy an element from one section of your document to another. See the demo to try it out.

The Code

This script is copyright (c) 2006 Elliot Swan under the 
Creative Commons Attribution-ShareAlike 2.5 license:


More information on this script can be found at: 



var Move =	{

  copy	:   function(e, target)	{ 
	    var eId      = $(e);
	    var copyE    = eId.cloneNode(true);
	    var cLength  = copyE.childNodes.length -1;
	    copyE.id     = e+'-copy';

	    for(var i = 0; cLength >= i;  i++)	{
	    if(copyE.childNodes[i].id) {
	    var cNode   = copyE.childNodes[i];
	    var firstId = cNode.id;
	    cNode.id    = firstId+'-copy'; }
  element:  function(e, target, type)	{
	    var eId =  $(e);
	    if(type == 'move') {

	    else if(type == 'copy')	{ 
	       this.copy(e, target);

How to use it

After you drop the object into your common JavaScript library, anytime you want to move an element you just call the following method:

Move.element('e', target', 'type');

This has three parameters. The first one, e, should be replaced by the element you wish to copy or move. Replace target with the element you wish to drop e into. The last parameter, type, should be replaced with one of two possible values: move, or copy. A value of move will move the element to the target, whereas a value of copy will copy it (D’oh).

Oh, and one more thing.

Yeah, I listen to too many Steve Jobs keynotes.

But really, there is one more thing. We haven’t discussed what to do with the ids of copied elements. As you should already know, an id should be unique–so they can’t just copy over. So what I’ve done is add -copy to the end of each copied id, in both the main element and all of its children. If the element’s children don’t have ids, none will be added.

Also note that this object uses the Prototype dollar function a few times, so if you aren’t including Prototype you can simply replace all instances of the $ sign with document.getElementById and you’ll be set. Or, just include the following little snippet:

/*  Prototype JavaScript framework, version 1.5.0_pre0
 *  (c) 2005 Sam Stephenson 
 *  Prototype is freely distributable under the terms of an MIT-style license.
 *  For details, see the Prototype web site: http://prototype.conio.net/
 * The Dollar Function:

function $() {
  var results = [], element;
  for (var i = 0; i < arguments.length; i++) {
    element = arguments[i];
    if (typeof element == 'string')
      element = document.getElementById(element);
  return results.length < 2 ? results[0] : results;

And as always, I’d be interested to hear your thoughts. swan