向 DOM 添加新元素时出现问题

Problems adding a new element to the DOM?

本文关键字:问题 元素 DOM 添加 新元素      更新时间:2023-09-26

试图向 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>​

脚本在<head>中,代码立即运行(它不是延迟的函数调用)。当您尝试运行<body>时,它不存在。

将脚本移动到</body>之前,或将其移动到函数中并调用它 onload

getElementsByTag不是document对象上的方法。你可能的意思是getElementsByTagName但这会返回一个 NodeList,而不是一个 HTMLElementNode。这就像一个数组。您需要从中拉出第一项,或者更好:

使用document.body

这是你想要的:

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

试试这个新的小提琴: 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]

<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