Search code examples
htmltypescriptlistinline

Appending <li> item to <ul> with TS


I have been trying to append "Avocado" to this list but then I get the error message

Uncaught TypeError: Cannot read properties of null (reading 'appendChild')

    <!DOCTYPE html >
    <html  lang="de">
    <head >
    <title >Am I Loaded ?! </title >
    <script>
        const element = document.getElementById("list")
        const elementText = document.createTextNode("Avocado")
        element.appendChild(elementText);
    </script>
    </head>
    <body>
    <h1>Meine Obstschale</h1>
    <ul id="list">
        <li >Apple </li >
        <li >Pear </li >
        <li >Orange </li >
        <li >Banana </li >
        </ul >
    </body >
    </html>

What am I doing wrong here, please?


Solution

  • The error tells you that you are trying to invoke the member function appendChild on a null object. This does not work because there are no member functions on a null object. In your code you only invoke appendChild once, which means that element is that null object. Knowing this, you can see that getElementById returned that null object. Either your ID does not exist or it is not loaded yet.

    tl;dr; You are running that Javascript before the elements of your page are loaded. You can place your script right before the closing body to circumvent this.

        <!DOCTYPE html >
        <html  lang="de">
        <head >
        <title >Am I Loaded ?! </title >
        
        </head>
        <body>
        <h1>Meine Obstschale</h1>
        <ul id="list">
            <li >Apple </li >
            <li >Pear </li >
            <li >Orange </li >
            <li >Banana </li >
        </ul >
        <script>
            const element = document.getElementById("list")
            const elementText = document.createTextNode("Avocado")
            element.appendChild(elementText);
        </script>
        </body >
        </html>