innerHTML Not Working For Select Drop Down For Internet Explorer – Solution

Hi Friends, Some days ago I was working on one project in which I Have to use Ajax to populate select drop down box of states when selecting one country from first select drop down box. Now i implemented it properly and I checked it in Mozilla, Google Chrome and it was working properly. But when I checked it in Internet Explorer then when selecting any country it is not populating states select box. I checked all things and finally I found that innerHTML was not working properly in Internet Explorer. I dont know what was the reason of that but I searched on Internet and found one block of code by which this solved my problem.

Below is black of code by which my problem solved in all browser, even in internet explorer 6. So I thought to share it here with my readers, So may be some days it would be helpful for some one.

function select_innerHTML(objeto,innerHTML){

    objeto.innerHTML = ""
    var selTemp = document.createElement("micoxselect")
    var opt;
    selTemp.id="micoxselect1"
    document.body.appendChild(selTemp)
    selTemp = document.getElementById("micoxselect1")
    selTemp.style.display="none"
    if(innerHTML.indexOf("<option")<0){//se não é option eu converto
        innerHTML = "<option>" + innerHTML + "</option>"
    }
    innerHTML = innerHTML.replace(/<option/g,"<span").replace(/<\/option/g,"</span")
    selTemp.innerHTML = innerHTML

    for(var i=0;i<selTemp.childNodes.length;i++){
  var spantemp = selTemp.childNodes[i];

        if(spantemp.tagName){
            opt = document.createElement("OPTION")

   if(document.all){ //IE
    objeto.add(opt)
   }else{
    objeto.appendChild(opt)
   }

   //getting attributes
   for(var j=0; j<spantemp.attributes.length ; j++){
    var attrName = spantemp.attributes[j].nodeName;
    var attrVal = spantemp.attributes[j].nodeValue;
    if(attrVal){
     try{
      opt.setAttribute(attrName,attrVal);
      opt.setAttributeNode(spantemp.attributes[j].cloneNode(true));
     }catch(e){}
    }
   }
   //getting styles
   if(spantemp.style){
    for(var y in spantemp.style){
     try{opt.style[y] = spantemp.style[y];}catch(e){}
    }
   }
   //value and text
   opt.value = spantemp.getAttribute("value")
   opt.text = spantemp.innerHTML
   //IE
   opt.selected = spantemp.getAttribute('selected');
   opt.className = spantemp.className;
  }
 }
 document.body.removeChild(selTemp)
 selTemp = null
}
// Use of this function
select_innerHTML(document.getElementById('country_state_id'),html);

So above is code by which you can solve innerHTML problem in innerHTML. Let me know if you have any problems in this code, I will try to solve it.

I am WordPress Developer India and If you have any projects regarding wordpress or PHP then contact me.