Вопрос

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>
Это было полезно?

Решение

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>

Другие советы

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!

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top