0

I was trying to make a custom drop down menu, and was sort of experimenting with different ways to do it. However, appendChild suddenly stopped working. When I checked the chrome console, it gave the error of "Uncaught TypeError: Cannot read property 'appendChild' of null" for line 26. I've used appendChild a lot before, and i've never had this kind of problem with it. I even opened up a different document I had previously made and copy + pasted a nearly identical line into it, and got the same error. Help?

<!doctype html>
<script>
function changeClassValue() {
    if(document.getElementById('dropDown').className == "up") {
            document.getElementById('dropDown').className = "down";
            numberValue = 1;
        } else if(document.getElementById('dropDown').className == "down") {
            document.getElementById('dropDown').className = "up";
            numberValue = 0;
        } else {

    }
changeTextVisibility();
}
function changeTextVisibility() {
    if(numberValue == 1) {
            newDiv.appendChild(newParagraph);
    } else if(numberValue == 0); {
            newDiv.appendChild(newParagraph);
 }
}
var numberValue;
var newDiv = document.createElement('div');
var newParagraph = document.createElement('p');
var newParagraphText = document.createTextNode('This is a drop down menu!');
document.body.appendChild(newDiv);
newParagraph.appendChild(newParagraphText); //this is line 26, and is what seems to be broken.
</script>
<style>

</style>

<body style="background-color: skyblue;">
<p id="dropDown" class="up" style="font-size: 25px; padding: 10px      10px;background-color: slategray; display: inline-block;"
onclick="changeClassValue();"><strong><u> >drop down menu< </u></strong></p>
</body>

1 Answers1

0

Move the JavaScript to the end of the body. Right before the </body> tag.

Also, validate your HTML at https://validator.w3.org

user2182349
  • 9,569
  • 3
  • 29
  • 41