CloneNode in Internet Explorer

When the following code is executed, IE throws an error: Object does not support this property or method - it refers 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 that source.options [i] has a cloneNode () method.

Thanks.

+7
javascript internet-explorer clonenode
source share
4 answers

IE requires

 new Option() 

construct.

 document.createElement( 'option' ); 

or

 cloneNode() 

will fail. Of course, all options work as expected in the right web browser.

+8
source share

In fact, cloneNode does not cause errors. Divide your code into smaller pieces to determine the source of the error correctly:

 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, returning it, as you have, all in one line:

 dest.appendChild(source.options[i].cloneNode( true )); 
+5
source share

I found this post helpful: IEs cloneNode is not actually cloned!

+1
source share
 <!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> 
0
source share

All Articles