2012-05-04 26 views
0

DOMに新しい要素を追加しようとしましたが、何をしようとしているのかによってさまざまなエラーが発生します。DOMに新しい要素を追加する際の問題?

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>​ 

答えて

3

スクリプトは<head>にあり、あなたのコードは、(それが遅れた関数呼び出しではありません)すぐに実行されます。 <body>は、実行しようとすると存在しません。

スクリプトを</body>の直前に移動するか、関数に移動してonloadとします。

getElementsByTagは、documentオブジェクトのメソッドではありません。おそらくgetElementsByTagNameを意味しますが、それはHTMLElementNodeではなくNodeListを返します。これは配列のようなものです。

使用document.bodyここ

0

が何をしたいです:

<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> 

、ここ

0

JSFiddle Demoは、この新しいとみているあなたはそれをオフ最初の項目を引っ張ったり、より良いする必要がありますフィドル: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>​ 

正しいsintaxは次のとおりです。document.getElementsByTagName("TagName")[index]

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.onloadhow touse it correctly

document.body

関連する問題