DOM节点层次(Document类型)

来源:互联网 发布:java object转date 编辑:程序博客网 时间:2024/05/16 08:03

2.Document类型

在浏览器中,document对象是Document类型的一个实例,表示整个HTML页面。同时它也是window对象的一个属性,因此可以将其作为全局对象来访问。

Document的特征:

  • nodeType的值为9
  • nodeName的值为”#document”
  • nodeValue的值为null
  • parentNode的值为null
  • ownerDocument的值为null
  • 其子节点可能是一个DocumentType(最多一个)、Element(最多一个)、ProcessingInstruction或Coment

(1).文档的子节点

子节点可能是一个DocumentType(最多一个)、Element(最多一个)、ProcessingInstruction或Coment。

document对象所具有的属性:

  • documentElement属性
    始终指向页面中的<html>元素,可以通过它或者childNodes列表来访问<html>
var html=document.documentElement;//取得对<html>的引用alert(html===document.childNodes[0]);//truealert(html===document.firstChild);//true
  • body属性
    直接指向<body>元素

(2).文档信息

  • title属性
    包含<title>属性中的文本

  • URL、domain和referrer属性

//取得完整的URLvar url=document.URL;//取得域名var domain=document.domain;//取得来源页面的URLvar referrer=document.referrer;

(3).查找元素( 重要)

  • getElementsById( )
    接收一个参数,就是要取得元素的ID
<div id="myDiv">some text</div>var div=document.getElementsById("myDiv");
  • getElementsByTagName( )
    接收一个参数,即要取得元素的标签名,而返回的是包含零或多个元素的NodeList。在HTML中这个方法会返回一个HTMLCollection的对象
var images=document.getElementsByTagName("img");alert(images.length);//输出图像的数量//可以用方括号语法或item()方法来访问HTMLCollection中的项alert(images[0].src);//输出第一个图像元素的src特性alert(images.item(0).src);//输出一个图像元素的src特性var allElements=document.getElementsByTagName("*");//传入*号 取得所有元素
  • getElementsByName()
    返回带有给定name特性的所有元素。最常用的是取得单选按钮。返回的也是一个HTMLCollection
<fieldset>//单选按钮的name特性值都是color,确保三个值中只有一个被发送给服务器,id则是将input和label对应    <legend>Which color do you want</legend>        <ul>            <li>                <input type="radio" value="red" name="color" id="colorred">                <label for="colorred">Red</label>            </li>            <li>                <input type="radio" value="green" name="color" id="colorgreen">                <label for="colorgreen>">green</label>            </li>            <li>                <input type="radio" value="blue" name="color" id="colorblue">                <label for="colorblue">blue</label>            </li>        </ul></fieldset>var radios=document.getElementByName("color");

(4)DOM一致性检测

检测浏览器实现了DOM的哪些部分或者说功能是很重要的。这个活由document.implementation.hasFeature( )来完成

var hasXmlDom=document.implementation.hasFeature("XML","1.0");

(5).文档写入

  • write()
<body>    <p>The current date and time is:        <script>            document.write("<strong>"+(new Date()).toString()+"</strong>");            //输出当前日期和时间,日期被包含在一个<strong>元素中,就像在普通HTML页面中一样        </script>    </p></body>
  • writeln()
    它和write()的区别就是会在字符串的末尾添加一个换行符(\n)