DonG
DonG

Reputation: 821

document.getElementById innerHTML not displaying

This should be a pretty easy thing to do, but it's not returning anything. The function love() should kick off, getting a simple number prompt, and spitting out a list of a few items that uses that starting number. the alert box correctly displays what I expect, but I want it to display on the screen. (this is but a small section of what I'm after, but it's the kernel of it). No text is displaying in the IE, FF, or Chrome...

<script type="text/javascript">
        function love()
        {
            var ncxElement="";
            var idNumber = prompt("Enter beginning number","");
            var myText=document.getElementById("here");
            for (var i=1;i<5;i++)
            {
                ncxElement+=("<navPoint class=\"other\" id=\"page_"+idNumber+"\">\n");
                idNumber++;
            }
                alert(ncxElement);
                myText.innerHTML=ncxElement;
        }
    </script>
    </head>
    <body onload="love()">
    <p id="here">Begin!</p>
    </body>

Upvotes: 1

Views: 5315

Answers (3)

ThinkingStiff
ThinkingStiff

Reputation: 65391

If you want to display HTML on your page (without it being parsed), use .textContent instead of .innerHTML and wrap it in a <pre> (to preserve the line breaks).

Demo: jsFiddle

Change:

myText.innerHTML=ncxElement;

To:

myText.textContent=ncxElement;

Change:

<p id="here">Begin!</p>

To:

<pre id="here">Begin!</pre>

Upvotes: 2

Ricardus
Ricardus

Reputation: 739

Your function just wraps elements inside another. There is no text inside or outside these elements to dipslay. Try inserting some random text before closing tags to see the result. Btw, the elements are successfully placed in the p tag.

Upvotes: 1

d_ethier
d_ethier

Reputation: 3911

navPoints are not valid html elements, so the browser doesn't know what to do with them. They are being added to the DOM, just not displayed unless you add styling to do so.

If you replace them with paragraph tags, it works fine. See the example here.

<script type="text/javascript">
    function love()
    {
        var ncxElement="";
        var idNumber = prompt("Enter beginning number","");
        var myText=document.getElementById("here");
        for (var i=1;i<5;i++)
        {
ncxElement+=("<p class=\"other\" id=\"page_"+idNumber+"\">"+idNumber+ "</p>");
            idNumber++;
        }
            alert(ncxElement);
            myText.innerHTML=ncxElement;
    }
</script>
</head>
<body onload="love()">
<p id="here">Begin!</p>
</body>

Upvotes: 1

Related Questions