繁体   English   中英

在向DOM添加新元素时遇到问题?

[英]Problems adding a new element to the 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>​

该脚本位于<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演示

尝试使用这个新的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>​

正确的语法是: 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM