Search code examples
javascripthtmlcssappendappendchild

Why does append.Child return me null when I use it in a Div but works when I put it on the body?


for some reason my code doesn't work. When I try to see what the console will return me it gives me the answer I want while returning me: "Uncaught TypeError: Cannot read property 'appendChild' of null" when I the same thing on for a Div.

This is my code please help me...

function addOnePropertie () {
    var theUl = document.createElement ("UL");
    var theText = document.createTextNode ("This is a paragraph.");
    theUl.appendChild (theText);
    document.getElementById('theUlDiv').appendChild (TheUl); 
}

<div class="divOne">
    <header>
        Sign Up an Object
    </header>

    <ul>
        <span class="spanObject"> Name of Object: </span>
        <input placeholder="Type any Name...">
    </ul>
        <hr class="inDiv">
    <ul>
        <span class="spanObject"> Name plus Value of Propertie One: </span>
        <input class="smallInput" placeholder="Name of Propertie..."> 
        <input class="smallInput" placeholder="Value of Propertie">
    </ul>
    <div id="theUlDiv">
    </div>
    <button class="addPropertie" onclick="addOnePropertie ();">
        Add a Propertie 
        <i class="material-icons" style="color: blue; font-size: 15px;"> 
            note_add 
        </i>
    </button>
</div>

As you see if I console.log (theUl) it returns me what I want a new Ul element, same if I try to put it in document.body.appendChild (theUl), but if I do it in the div it doesn't work, please help me out :D


Solution

  • The way to debug this will be, try to query in your browser console for the element, document.getElementById('theUlDiv') and you will find that it will return null because your markup doesn't have an element with id='theULDiv' either use document.getElementsByClassName('theUlDiv')[0] or change your markup to add the id to the element. Edit: There is another error in this line .appendChild (TheUl); inside appendChild method you are passing an undefined variable. your actual variable is theUl but you have capital 'T'