开发者

Using innerHTML to add ordered list fails in IE

开发者 https://www.devze.com 2023-01-02 08:37 出处:网络
I\'m using the following Javascript code to populate a DIV with an ordered list: // send script back in split list

I'm using the following Javascript code to populate a DIV with an ordered list:

// send script back in split list
var scriptList = script.split("\n");
var finalScript = "<ol>\n";
var count = 0;
while(scriptList.length >= count) {
    if((scriptList[count]=="") || (scriptList[count] == undefined))  {
        count ++;
        continue;
    }

    finalScript = finalScript + "<li>" + scriptList[count] + "</li>\n";
    count ++;
}
finalScript = finalScript + "</ol>";
scriptingDiv.innerHTML = finalScript;

In firefox, if i look in the DOM using Firebug, this correctly translates to the following and correctly displays an ordered list.

<ol>
<li>This开发者_Go百科 is the first item in the list</li>
<li>This is the second item in the list</li>
</ol>

In IE, it displays as if the </li> tags are <br /> tags and ignores all the other tags, like this:

This is the first item in the list

This is the second item in the list

Do I need to dynamically add the ordered list to the DOM for this to work? As opposed to just setting the html code in the div using .innerHTML?

TIA


Do I need to dynamically add the ordered list to the DOM for this to work? As opposed to just setting the html code in the div using .innerHTML?

Yes

var scriptList = script.split("\n");
var count = 0;
var ol = document.createElement("ol");

    for(var index=0; index<scriptList.length; index++) {
        if(scriptList[index]!="")  {
            var li = document.createElement("li");
            li.innerHTML=scriptList[index];
            ol.appendChild(li);
        }
    }

scriptingDiv.appendChild(ol);


Why not use dom methods instead? IE:

myOL = document.createElement("ol");
myLI = document.createElement("li");
myTxt = document.createTextNode("My Text!");
myLI.appendChild(myTxt);
myOL.appendChild(myLI);

etc

0

精彩评论

暂无评论...
验证码 换一张
取 消