0

Trying to add a new element to the DOM but I get all sorts of errors depending on what I try to do.

http://jsfiddle.net/pRVAd/

<html>
<head>
    <script>
        var newElement = document.createElement("pre");
        var newText = document.createTextNode("Contents of the element");
        newElement.appendChild(newText);
        document.getElementsByTag("body").appendChild(newElement);
    </script>
</head>
<body>
    <p>Welcome</p>
</body>

</html>​
antonpug
  • 13,724
  • 28
  • 88
  • 129

4 Answers4

3

The script is in the <head> and your code runs immediately (it is not a delayed function call). The <body> does not exist when you try to run it.

Move the script to just before </body> or move it into a function and call it onload.

getElementsByTag is not a method on the document object. You probably mean getElementsByTagName but that returns a NodeList, not an HTMLElementNode. This is like an array. You need to pull the first item off it, or better:

Use document.body

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

Here is what you want:

   <html>
    <head>
        <script>
            var newElement = document.createElement("pre");
            var newText = document.createTextNode("Contents of the element");
            newElement.appendChild(newText);
            document.body.appendChild(newElement);
        </script>
    </head>
    <body>
        <p>Welcome</p>
    </body>

and here is JSFiddle Demo

Zaheer Ahmed
  • 28,160
  • 11
  • 74
  • 110
0

Try with this new Fiddle: http://jsfiddle.net/pRVAd/1/

<html>
<head>
    <script>
        function doTheThing() {
            var newElement = document.createElement("pre");
            var newText = document.createTextNode("Contents of the element");
            newElement.appendChild(newText);
            document.getElementsByTagName("body")[0].appendChild(newElement);
        }
    </script>
</head>
<body>
    <input type="button" value="Do The Thing" onclick="doTheThing()">    
    <p>Welcome</p>
</body>

<html>​

The correct sintax is: document.getElementsByTagName("TagName")[index]

MatuDuke
  • 4,997
  • 1
  • 21
  • 26
0
<html>
<head>
  <script>
    // This function will be executed once that the DOM tree is finalized
    // (the page has finished loading)
    window.onload = function() {
      var newElement = document.createElement("pre");
      var newText = document.createTextNode("Contents of the element");
      newElement.appendChild(newText);
      // You have to use document.body instead of document.getElementsByTag("body")
      document.body.appendChild(newElement);  
    }
  </script>
</head>
<body>
  <p>Welcome</p>
</body>
</html>​

window.onload and how to use it correctly.

document.body

Community
  • 1
  • 1
Esteban Küber
  • 36,388
  • 15
  • 79
  • 97