views:

102

answers:

3

While executing the following code IE throws the error -- Object doesn't support this property or method -- referring to the cloneNode() method. 'i' is the loop counter, source and dest are both HTML select elements.

dest.options[dest.options.length] = source.options[i].cloneNode( true );

FF and Chrome behave as expected. Any ideas on how to get IE to execute cloneNode()? The IE 8 debugger shows source.options[i] does have a cloneNode() method.

Thanks.

+1  A: 

IE requires the

new Option()

construct.

document.createElement( 'option' );

or

cloneNode()

will fail. Of course, all options work as expected in a proper web browser.

Mark
+1 for "proper web browser" :)
Pumbaa80
A: 
<!doctype html>
<html lang="en">
<head>
<meta charset= "utf-8">
<title>Untitled Document</title>
<style>
p, select,option{font-size:20px;max-width:640px}
</style>
<script>

function testSelect(n, where){
    var pa= document.getElementsByName('testselect')[0];
    if(!pa){
        pa= document.createElement('select');
        where.appendChild(pa);
        pa.name= 'testselect';
        pa.size= '1';
    }
    while(pa.options.length<n){
        var i= pa.options.length;
        var oi= document.createElement('option');
        pa.appendChild(oi);
        oi.value= 100*(i+1)+'';
        oi.text= oi.value;
    }
    pa.selectedIndex= 0;
    pa.onchange= function(e){
        e= window.event? event.srcElement: e.target;
        var val= e.options[e.selectedIndex];
        alert(val.text);
    }
    return pa;
}
window.onload= function(){
    var pa= testSelect(10, document.getElementsByTagName('h2')[0]);
    var ox= pa.options[0];
    pa.appendChild(ox.cloneNode(true))
}

</script>
</head>

<body>
<h2>Dynamic Select:</h2>
<p>You need to insert the select into the document, 
and the option into the select,
before IE grants the options any attributes.
This bit creates a select element and 10 options,
and then clones and appends the first option to the end.
<br>It works in most browsers.
</p>
</body>
</html>
kennebec
A: 

Actually, cloneNode isn't throwing any error. Break your code down into smaller chunks to properly identify the source of the error:

var origOpt = source.options[i];
var clonedOpt = origOpt.cloneNode( true );  // no error here
var destOptLength = dest.options.length;
dest.options[destOptLength] = clonedOpt;    // error!
dest.options.add(clonedOpt);                // this errors too!

dest.appendChild(clonedOpt);                // but this works!

Or, putting it back the way you had it, all on one line:

dest.appendChild(source.options[i].cloneNode( true ));
gilly3