2012-05-04 187 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,但是它返回一個NodeList,而不是HTMLElementNode。這就像一個數組。你需要拉的第一個項目關閉它,或者更好的

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

,這裏是JSFiddle Demo

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]

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