以下方法獲取的爲HTMLCollection對象
document.images //所有img元素
document.links //所有帶href屬性的a元素和area元素
document.anchors //所有帶name屬性的a元素
document.forms //所有form元素
document.scripts //所有script元素
document.applets //所有applet元素
document.embeds //所有embed元素
document.plugins //document.與embeds相同
document.getElementById("table").children
document.getElementById("table").tBodies
document.getElementById("table").rows
document.getElementById("row").cells
document.getElementById("Map").areas
document.all //HTMLAllCollection,與HTMLCollection類似
document.getElementById("f2").elements //HTMLFormControlsCollection extends HTMLCollection
document.getElementById("s").options //HTMLOptionsCollection extends HTMLCollection
以下方法獲取的爲NodeList對象
document.getElementsByName("bing")
document.getElementsByClassName("no")
document.getElementsByTagName("a")
document.getElementsByTagNameNS("*", "a")
document.querySelectorAll("a")
document.getElementById("table").childNodes
document.styleSheets //StyleSheetList,與NodeList類似
一、相同點
HTMLCollection與NodeList有很大部分相似性
1、都是類數組對象
都有length屬性,可以通過for循環迭代
2、都是隻讀的
3、都是實時的,即文檔的更改會立即反映到相關對象上面
var f = document.forms;
console.log(f.length); //2
var temp = document.createElement("form");
document.body.appendChild(temp);
console.log(f.length); //3
有一個例外,就是document.querySelectorAll返回的NodeList不是實時的
4、都有item()方法
可以通過item(index)或item("id")獲取元素
5、可以通過屬性的方式訪問元素,如document.forms.f1(f1爲form的id)
二、不同點
1、HTMLCollection對象具有namedItem()方法,可以傳遞id或name獲得元素
2、HTMLCollection的item()方法和通過屬性獲取元素(document.forms.f1)可以支持id和name,而NodeList對象只支持id
附:示例代碼所使用的HTML
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
body
{
margin:0px;
}
</style>
<link type="text/css" rel="stylesheet" href="http://fonts.googleapis.com/css?family=Special+Elite" />
<script type="text/javascript">var hzt = "sxn"</script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
</head>
<body>
<form id="f1">
<a id="a1" href="http://www.google.com.hk/">谷歌</a>
<a id="a2" name="baidu" href="http://www.baidu.com/">百度</a>
</form>
<form id="f2">
<a name="bing" href="http://cn.bing.com/">必應</a>
<a href="http://www.so.com/">360搜索</a>
<select id="s">
<option>1</option>
<option>2</option>
</select>
</form>
<img src="http://www.baidu.com/img/0616-PC_b24258be2a4f5cd71df9066e31a0ccf4.gif" usemap="#Map" />
<map id="Map" name="Map">
<area name="ma1" shape="rect" coords="200,46,261,84" href="http://www.baidu.com" target="_blank">
<area shape="circle" coords="43,63,40" href="#">
<area shape="poly" coords="156,76">
</map>
<img src="http://p1.qhimg.com/d/_onebox/search.png" class="no" />
<table id="table" cellpadding="0" cellpadding="0" border="1">
<thead>
<tr>
<th>1</th>
<th>2</th>
</tr>
</thead>
<tbody>
<tr id="row">
<td>曹州</td>
<td>菏澤</td>
</tr>
</tbody>
<tbody>
<tr>
<td>國花</td>
<td>牡丹</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>a</td>
<td>b</td>
</tr>
</tfoot>
</table>
</body>
</html>