children 属性返回元素的子元素的集合,是一个 HTMLCollection 对象。
提示: 根据子元素在元素中出现的先后顺序进行排序。使用 HTMLCollection对象的 length属性获取子元素的数量,然后使用序列号(index,起始值为0)访问每个子元素。
children 属性与 childNodes 属性的差别:
属性 | 谷歌 | IE | 火狐 | 苹果 | opera |
---|---|---|---|---|---|
children | 2.0 | 9.0* | 3.5 | 4.0 | 10.0 |
注:IE6 到 IE8 完全支持 children 属性,但是,返回元素节点和注释节点,IE9 以上版本只返回元素节点。
element.children
返回值: | HTMLCollection 对象,表示一个元素节点的集合,元素在集合中的顺序是在源码中的顺序。 |
---|---|
DOM 版本 | DOM 1 |
获取 body 元素的子元素集合:
<!DOCTYPE html> <html> <title>Web176教程网(web176.com)</title> <body> <p>点击按钮获取 body 元素子元素的标签名。</p> <button >
查看 div 有几个子元素:
<!DOCTYPE html> <html> <title>Web176教程网(web176.com)</title> <head> <style> div { border: 1px solid black; margin: 5px; } </style> </head> <body> <p>点击按钮查看 div 有几个子元素。</p> <button >
修改 div 元素第二个子元素的背景颜色:
<!DOCTYPE html> <html> <title>Web176教程网(web176.com)</title> <head> <style> div { border: 1px solid black; margin: 5px; } </style> </head> <body> <p>点击按钮为 div 的第二个(索引为 1)子元素添加背景颜色。</p> <button >
获取 select 元素中第三个(索引为 2) 子元素的文本:
<!DOCTYPE html> <html> <title>Web176教程网(web176.com)</title> <body> <p>点击按钮获取 select 元素中第三个(索引为 2) 子元素的文本:</p> <select id="mySelect" size="4"> <option>Audi</option> <option>BMW</option> <option>Saab</option> <option>Volvo</option> </select> <br><br> <button >
修改 body 元素所有子元素的背景颜色:
<!DOCTYPE html> <html> <title>Web176教程网(web176.com)</title> <body> <p>点击按钮修改 body 元素所有子元素的背景颜色。</p> <button >