Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
562 views
in Technique[技术] by (71.8m points)

dom - 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);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your code works well you just mistyped this line of code:

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

change it with this: (The "B" should be capitalized.)

document.getElementById('lc').appendChild(element);  

HERE IS MY EXAMPLE:

<html>
<head>

<script>

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);

}

</script>

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

<div id="lc" style="background: blue; height: 150px; width: 150px;
}" onclick="test();">  
</div>
</body>

</html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...