Creating a div element inside a div element in javascript

后端 未结 3 745
挽巷
挽巷 2020-12-05 13:20

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:



        
相关标签:
3条回答
  • 2020-12-05 13:31

    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>

    0 讨论(0)
  • 2020-12-05 13:41

    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.

    0 讨论(0)
  • 2020-12-05 13:48

    '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);
     }
    
    0 讨论(0)
提交回复
热议问题