[javascript] Creating a div element inside a div element in javascript

I'm trying a very basic example of creating a div inside an already existing div.

It doesn't seem to be working when I use:

document.getElementbyId('lc').appendChild(element)

but works fine when I do this:

document.body.appendChild(element)

Do I need to add windows.onload function? Though it doesn't work even then!

HTML code:

<body>
    <input id="filter" type="text" placeholder="Enter your filter text here.." onkeyup = "test()" />

    <div id="lc">  
    </div>
</body>

JS code:

function test()
{
    var element = document.createElement("div");
    element.appendChild(document.createTextNode('The man who mistook his wife for a hat'));
    document.getElementbyId('lc').appendChild(element);
    //document.body.appendChild(element);
}

This question is related to javascript dom createelement

The answer is


Yes, you either need to do this onload or in a <script> tag after the closing </body> tag, when the lc element is already found in the document's DOM tree.


'b' should be in capital letter in document.getElementById modified code jsfiddle

function test()
{

var element = document.createElement("div");
element.appendChild(document.createTextNode('The man who mistook his wife for a hat'));
document.getElementById('lc').appendChild(element);
 //document.body.appendChild(element);
 }