Javascript Element How to - Create a div element inside a div element with text content








Question

We would like to know how to create a div element inside a div element with text content.

Answer


<!--from   ww w.  j  av a 2 s.  c om-->
<!DOCTYPE html>
<html>
<body>
    <p>Type in the text field</p>
  <input id="filter" type="text"
    placeholder="Enter your filter text here.." onkeyup="test()" />
  <div id="lc"></div>
  <script>
function test(){
    var element = document.createElement("div");
    element.appendChild(document.createTextNode('typed'));
    document.getElementById('lc').appendChild(element);
}
</script>
</body>
</html>

The code above is rendered as follows: