Search code examples
javascripthtmlappendchildcreateelement

createElement and appendChild in JavaScript


I am trying to figure out why the createElement and appendChild aren't working. I believe I've got my code correct so I'm not too sure why it's not working... (I am using IE 10)

CODE UPDATED

JavaScript File:

var myObj = {

   firstName: "John",
   lastName: "Smith"
};

HTML File:

<!DOCTYPE html />
<html>
<title>The Data Structure</title>
<body>

<script type="text/javascript" src="TheData.js">

var theElement = document.createElement('p');
var theText = document.createTextNode(myObj.firstName);
theElement.appendChild(theText);
document.body.appendChild(theElement);

</script>
</body>
</html>

Solution

  • The issue is that you both supply a src on your script tag and provide content within it. That's invalid, you can do one or the other, not both. Most browsers will use the src and disregard the content.

    Separate from that, creating an element doesn't put it in the DOM. You have to add it somewhere (via appendChild or insertBefore or similar).

    So perhaps:

    <script src="TheData.js"></script>
    <!-- Note: Two separate script elements -->
    <script>
    var theElement = document.createElement('p');
    var theText = document.createTextNode(myObj.firstName);
    theElement.appendChild(theText);
    document.body.appendChild(theElement); // <==== Note: Adding `the Element` to the DOM
    </script>