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