document.body和document.getElementByTagName("body")區(qū)別是什么?
JavaScript進階篇9-16這一節(jié)的練習(xí)中,要在body中調(diào)用函數(shù)創(chuàng)建一個鏈接。在使用appendChild()方法往body節(jié)點下面添加子節(jié)點時,用getElementByTagName("body")獲取父節(jié)點body,然后再調(diào)用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")獲取父節(jié)點呢?
2016-06-06
document.getElementsByTagName("body")[0]少寫了s,雖然只有一個。但是也要寫[0]
2016-06-05
我覺得是因為body是比較大的元素節(jié)點,所以不能用?document.getElementsByTagName 去獲取他,規(guī)定只能用document.body獲取,