Jump to content

Need help Adding an "li" tag using DOM


eldan88

Recommended Posts

Hey Guys. I just ran into another small challenge. I am trying to add a new element using the DOM, just so that I can get the hang of things. I know it seems very basic, but for some reason it doesn't seem to be working for me.

 

All I am trying to do, Is simple add a new li with the innerHTML called "this is some text". I know that innerHTML is not the best way of adding text nodes, but I just want to start with innerHTML, before working with text nodes.

 

Any advice as to why its not working for me? Below is my code!

 

Thanks

<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
          <script> 
       
    var list = document.getElementById("list_items");

var myNewElement = document.createElement("li");
myNewElement.innerHTML = "This is some new text";
list.appendChild("myNewElement");
        </script>
    </head>
    <body>
        <ul id="list_items"> 
            <li>Test 1 </li>
           
        
        </ul>
        
      
    </body>
</html>

Link to comment
https://forums.phpfreaks.com/topic/283870-need-help-adding-an-li-tag-using-dom/
Share on other sites

Hmm, it was either that, or the other problem:  you fed a string instead of an object to appendChild.

This seems to work OK:
 

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
          <script>
             function myFunct () { //a function; we'll call it once the DOM loads.
                'use strict';
                var list, myNewElement;
                list = document.getElementById("list_items");
                myNewElement = document.createElement("li");
 
                myNewElement.innerHTML = "This is some new text";
                list.appendChild(myNewElement); // not "myNewElement", which is a string, but the obj/var itself
             }
        </script>
    </head>
    <body onload="javascript:myFunct();">
        <ul id="list_items">
            <li>Test 1 </li>
 
 
        </ul>
 
 
    </body>
</html>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.