How I discovered ‘cloneNode’

So I was trying to copy all the <option> elements from one <select> element to another.

I had a drop-down list of countries, and I wanted users to be able to select more than one country, so had a ‘Add another country’ button that created a new drop-down; copying into it the <option> elements from the first drop-down.

I did the old

var someVar = firstSelect.getElementsByTagName('option');

and then ran a for loop that wrote (using appendChild) all the objects in someVar to a new <select> element. I thought this should be sweet.

But no. It seemed that random option elements were disappearing from the initial <select> element, such that after you’d added a few extra country drop-downs, there were no <option> elements left in the first drop-down to copy from!

As it turns out, someVar actually contains the original option elements themselves, and so I was moving them, instead of copying them.

cloneNode

So, after a bit of googling, I discovered cloneNode.

Using

var justATempVar = someVar[i].cloneNode(true);

in my loop; then writing justATempVar to the new <select> element worked a treat; the original <select> <option>s were left unmolested, and I got my new nodes.

In hindsight, I should have just cloned the <select> node and renamed it, which I will probably do when I get in to work tomorrow. I’m not sure which method is more resource-hungry, but I’m guessing it’s the loop.

I’m not sure whether I’m supposed to be using cloneNode or not, but it seems to work in the versions of IE and Firefox that I’m developing in. Proper testing is yet to see if it works in all our supported browsers.

FYI: The boolean parameter that cloneNode accepts tells the method whether or not to clone child nodes also. This is where I found out about cloneNode.

This entry was posted in Coding, JavaScript. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *