Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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); } 
like image 233
Komal Waseem Avatar asked Sep 27 '12 13:09

Komal Waseem


People also ask

How do I create a div within a div?

To start, wrap a div element in another div element in your HTML. Give the inner div a class name like "child" and the outer div a class name like "parent." Then in your CSS, use the class selector .parent to style the outer div. Set its height, width, and background color.

How do I get an element inside a div?

We can use document. querySelector on to select a div and then select an element within it with the given class after that. We just call querySelector on the element with the ID mydiv to select items inside that div. Therefore, innerDiv is the div with the class myclass .

Can I put a div inside a script?

You can add <script></script> inside a DIV tag. Just check on w3c, it is valid HTML.


1 Answers

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>
like image 120
Develoger Avatar answered Oct 02 '22 00:10

Develoger