document.body和document.getElementByTagName("body")區別是什么?
JavaScript進階篇9-16這一節的練習中,要在body中調用函數創建一個鏈接。在使用appendChild()方法往body節點下面添加子節點時,用getElementByTagName("body")獲取父節點body,然后再調用appendChild()時,會報錯:undefined function;
????var?main?=?document.getElementsByTagName("body"); ????var?a?=?document.createElement("a"); ????a.href?=?url; ????a.innerHTML?=?text; ????a.style.color?=?"red"; ????main.appendChild(a);
使用如下代碼就沒問題:
????var?main?=?document.body; ????var?a?=?document.createElement("a"); ????a.href?=?url; ????a.innerHTML?=?text; ????a.style.color?=?"red"; ????main.appendChild(a);
請問,為什么不能用document.getElementByTagName("body")獲取父節點呢?
2016-06-06
document.getElementsByTagName("body")[0]少寫了s,雖然只有一個。但是也要寫[0]
2016-06-05
我覺得是因為body是比較大的元素節點,所以不能用?document.getElementsByTagName 去獲取他,規定只能用document.body獲取,