0

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>

2 Answers 2

2

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>
Sign up to request clarification or add additional context in comments.

1 Comment

A small detail noted by Crazy Train: it should be myObj.firstName (lowercase f) in the line that creates the text node.
2

You never append theElement to the document! Add one more line at the end:

document.body.appendChild(theElement);

As a side note, what's this immediately invoked function for?

(function () {
return myObj.firstName;
}());

It does nothing!

2 Comments

Yea that anonymous function will turn into something. Just a placeholder for now. Kind of one of those things I started on but didn't finish.
Also, myObj.FirstName !== myObj.firstName

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.