0

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

4 に答える 4

3

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

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

getElementsByTagdocumentオブジェクトのメソッドではありません。あなたはおそらく意味getElementsByTagNameしますが、それはHTMLElementNodeではなくNodeListを返します。これは配列のようなものです。あなたはそれから最初のアイテムを引っ張る必要があります、またはより良い:

使用するdocument.body

于 2012-05-04T12:23:33.207 に答える
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>

これがJSFiddleデモです

于 2012-05-04T12:26:36.103 に答える
0

この新しいフィドルを試してみてください: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]

于 2012-05-04T12:28:25.573 に答える
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それを正しく使用する方法

document.body

于 2012-05-04T12:33:03.573 に答える