Categories: DOM对象tips

HTML DOM children 属性 | DOM 对象:HTML DOM 元素对象

返回到:DOM 对象:HTML DOM 元素对象

定义和用法

children 属性返回元素的子元素的集合,是一个 HTMLCollection 对象。

提示: 根据子元素在元素中出现的先后顺序进行排序。使用 HTMLCollection对象的 length属性获取子元素的数量,然后使用序列号(index,起始值为0)访问每个子元素。

children 属性与 childNodes 属性的差别:

  • childNodes 属性返回所有的节点,包括文本节点、注释节点;
  • children 属性只返回元素节点;

浏览器支持

属性谷歌IE火狐苹果opera
children2.09.0*3.54.010.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 >
terry

这个人很懒,什么都没有留下~

Share
Published by
terry

Recent Posts