定义和用法
children 属性返回元素的子元素的集合,是一个 HTMLCollection 对象。
提示: 根据子元素在元素中出现的先后顺序进行排序。使用 HTMLCollection对象的 length属性获取子元素的数量,然后使用序列号(index,起始值为0)访问每个子元素。
children 属性与 childNodes 属性的差别:
- childNodes 属性返回所有的节点,包括文本节点、注释节点;
- children 属性只返回元素节点;
浏览器支持
| 属性 | 谷歌 | 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 onclick="myFunction()">点我</button>
<p id="demo"></p>
<script>
function myFunction() {
var c = document.body.children;
var txt = "";
var i;
for (i = 0; i < c.length; i++) {
txt = txt + c[i].tagName + "<br>";
}
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>查看 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 onclick="myFunction()">点我</button>
<div id="myDIV">
<p>第一个 p 元素 (索引为 0)</p>
<p>第二个 p 元素 (索引为 1)</p>
</div>
<p id="demo"></p>
<script>
function myFunction() {
var c = document.getElementById("myDIV").children.length;
document.getElementById("demo").innerHTML = c;
}
</script>
</body>
</html>修改 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 onclick="myFunction()">点我</button>
<div id="myDIV">
<p>第一个 p 元素</p>
<p>第二个 p 元素</p>
</div>
<script>
function myFunction() {
var c = document.getElementById("myDIV").children;
c[1].style.backgroundColor = "yellow";
}
</script>
</body>
</html>获取 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 onclick="myFunction()">点我</button>
<p id="demo"></p>
<script>
function myFunction() {
var c = document.getElementById("mySelect").children;
document.getElementById("demo").innerHTML = c[2].text;
}
</script>
</body>
</html>修改 body 元素所有子元素的背景颜色:
<!DOCTYPE html>
<html>
<title>Web176教程网(web176.com)</title>
<body>
<p>点击按钮修改 body 元素所有子元素的背景颜色。</p>
<button onclick="myFunction()">点我</button>
<h2>我是 h2 元素</h2>
<div>我是 div 元素</div>
<span>我是 span 元素</span>
<script>
function myFunction() {
var c = document.body.children;
var i;
for (i = 0; i < c.length; i++) {
c[i].style.backgroundColor = "red";
}
}
</script>
</body>
</html>作者:terry,如若转载,请注明出处:https://www.web176.com/javascriptbook/domtips/4333.html
支付宝
微信