Home >Web Front-end >JS Tutorial >JavaScript Document Object Model-Document type

JavaScript Document Object Model-Document type

黄舟
黄舟Original
2017-01-20 14:27:561527browse

JavaScript represents documents through the Document type. In the browser, the document object is an instance of HTMLDocument and represents the entire HTML page. And the Document object is an instance of the window object, so it can be accessed as a global object. Document type nodes have the following characteristics:

  • The value of nodeType is 9.

  • The value of nodeName is "#document".

  • The value of nodeValue is null.

  • The value of parentNode is null.

Its child nodes may be a DocumentType (at most one), Element (at most one), ProcessingInstruction or Comment.

The Document type can represent HTML pages or other XML-based documents. The most common application is the document object as an HTMLDocument instance. Through this document object, you can not only obtain information related to the page, but also manipulate the appearance of the page and its underlying structure.

Sub-nodes of the document

Although the DOM standard stipulates that the sub-nodes of the Document node can be DocumentType, Element, ProcessingInstruction or Comment, there are two built-in shortcuts for accessing its sub-nodes. Way. The first is the documentElement attribute, which always points to the element of the HTML page. The other is to access the document element through the childNodes list, but the element can be accessed more quickly through the documentElement attribute. The following is an example:

<html>
    <body>
         
    </body>
</html>

After the above page is parsed by the browser, its document only contains one child node and the element. The code to access this element through the documentElement attribute and childNodes list is as follows:

//取得<html>元素的引用
var html = document.documentElement;
alert(html === document.childNodes[0]);     //true
alert(html === document.firstChild);        //true

The above example shows that the values ​​of documentElement, firstChild and childNodes[0] are the same, and they all point to the element.

As an instance of HTMLDocument, the document object also has a body attribute, which directly points to the

attribute. document.body is a property we often use in development:
var body = document.body;

All browsers support the document.documentElement property and document.body property.

Another possible child node of Document is DocumentType. The tag is usually regarded as an entity different from other parts of the document. It can be accessed through the doctype attribute.

var doctype = document.doctype;     //获取<!DOCTYPE>的引用

Properties and methods of document object

The document object is a property of the window object. When the window is divided into several frames, each frame is a property of the window object, and the frame itself is actually an instance of the window object. The common attributes of the document object are shown in the following table:

JavaScript Document Object Model-Document type

Listed above are some commonly used document attributes. To view all document attributes supported by the current browser, you can use the following Method:

var attrs = new Array();
for(var property in window.document) {
    attrs.push(property);
    attrs.sort();
}
document.write("<table>");
for(var i=0;i<attrs.length;i++){
    if(i == 0){
        document.write("<tr>");
    }
    if(i > 0 && i%5 == 0){
        document.write("</tr><tr>");
    }
    document.write("<td>" + attrs[i] + "</td>");
}
document.write("</table>");

The above code will print the document attributes supported by the current browser in alphabetical order and then move the table to the page.

In the attributes of the document object above, the URL, domain and referrer attributes are related to the request of the web page. The URL attribute contains the complete URL address, and the page address of the clue in the address bar. The domain attribute only contains the domain name of the page, while the referrer attribute stores the URL address of the page linked to the current page. In the absence of a source page, the referrer attribute may contain an empty string. All this information is in the HTTP request headers, but we can access them using JavaScript.

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

Finding elements

In DOM applications, the most common operation is to obtain a reference to a certain element or a group of elements, and then perform some operations. The operation of obtaining elements can be completed through the following methods of the document object.

  • document.getElementById()

  • document.getElementsByTagName

  • ##document.getElementsByName()

The first method document.getElementById() receives a parameter: the ID of the element to be obtained. Returns the element if it is found, otherwise returns null. If there are multiple elements with the same ID in the page, the getElementById() method only returns the first element in the document. In IE browsers of IE7 and below, if the name attribute of the form element is the same as the element ID to be found, the form element will also be returned, for example:

<input type="text" name="someId" value="text value">
<div id="someId">div</div>

当使用document.getElementById("someId")来查找元素的时候,IE7浏览器会将元素返回。而其它浏览器则是返回div元素。

另一个经常使用的方法是document.getElementsByTagName,通过标签名来查找元素。该方法接收一个参数:要查找的标签名称。它会返回0个或多个元素的NodeList。在HTML文档中,该方法返回一个HTMLCollection对象,称为“动态”集合。例如,下面的代码获取页面中所有的JavaScript Document Object Model-Document type元素,并返回一个HTMLCollection:

var images = document.getElementByTagName("img");

与NodeList相似,可以使用方括号语法或item()方法来访问HTMLCollection对象:

alert(images.length);           //图片的数量
alert(images[0].src);           //第一张图片的src属性
alert(images.item(0).src);      //第一张图片的src属性

HTMLCollection对象还有一个方法:namedItem(),使用这个方法可以通过元素的name属性取得集合中的项。例如上面的图片集合中,如果有一张图片的name属性为mypic:

<img  src="demoimg.jpg" name="mypic" alt="JavaScript Document Object Model-Document type" >

那么就可以通过下面的方法从images变量中获取这张图片:

var mypic = images.namedItem("mypic");

如果想要获取页面中的所有元素,可以通过在getElementByTagName()方法中传入“*”通配符来获取。

var allElements = document.getElementByTagName("*");

第3个获取元素的方法是HTMLDocument特有的方法:getElementByName()。该方法会返回指定name属性的所有元素。例如下面的代码:

<ul>
    <li><input type="text" name="author" value="author1"></li>
    <li><input type="text" name="author" value="author2"></li>
    <li><input type="text" name="author" value="author3"></li>
</ul>
var authors = document.getElementByName("author");

上面的代码会返回所有的li元素。同样,getElementByName()方法也会返回一个HTMLCollection对象。

 HTML5中的querySelector和querySelectorAll方法

除了上面的三个查找元素的方法之外,在HTML5向Web API新引入了新的document.querySelector和document.querySelectorAll方法用来更方便地从DOM选取元素,功能类似于jQuery的选择器。

这两个方法使用差不多的语法,都是接收一个字符串参数,这个参数需要是合法的CSS选择语法。

element = document.querySelector(&#39;selectors&#39;);
elementList = document.querySelectorAll(&#39;selectors&#39;);

其中参数selectors 可以包含多个CSS选择器,用逗号隔开。

element = document.querySelector(&#39;selector1,selector2,...&#39;);
elementList = document.querySelectorAll(&#39;selector1,selector2,...&#39;);

使用这两个方法无法查找带伪类状态的元素,比如querySelector(':hover')不会得到预期结果。

querySelector方法返回满足条件的单个元素。按照深度优先和先序遍历的原则使用参数提供的CSS选择器在DOM进行查找,返回第一个满足条件的元素。

element = document.querySelector(&#39;div#container&#39;);//返回id为container的首个div
element = document.querySelector(&#39;.foo,.bar&#39;);//返回带有foo或者bar样式类的首个元素

querySelectorAll方法返回所有满足条件的元素,结果是个nodeList集合。查找规则与前面所述一样。

elements = document.querySelectorAll(&#39;div.foo&#39;);//返回所有带foo类样式的div

但需要注意的是返回的nodeList集合中的元素是非实时(no-live)的,想要区别什么是实时非实时的返回结果,请看下面的例子:

<div id="container">
    <div></div>
    <div></div>
</div>
//首先选取页面中id为container的元素
container=document.getElementById(&#39;#container&#39;);
console.log(container.childNodes.length)//结果为2
//然后通过代码为其添加一个子元素
container.appendChild(document.createElement(&#39;div&#39;));
//这个元素不但添加到页面了,这里的变量container也自动更新了
console.log(container.childNodes.length)//结果为3

通过上面的例子就很好地理解了什么是会实时更新的元素。document.getElementById返回的便是实时结果,上面对其添加一个子元素后,再次获取所有子元素个数,已经由原来的2个更新为3个(这里不考虑有些浏览器比如Chrome会把空白也解析为一个子节点)。

 文档的写入

document对象可以将输出流写入到网页中,它有4个方法:write()、writeln()、open()和close()。其中,write()和writeln()方法接收一个字符串参数,即要写入到输出流的文本。write()方法会原样写出,而writeln()方法会在字符串的末尾添加一个换行符(\n)。在页面加载的过程中,可以使用这两个方法来动态的添加内容,例如下面的代码:

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <p>当前的时间为:
    <script type="text/javascript">
    document.write("<strong>"+(new Date()).toString()+"</strong>");
    </script>
    </p>
</body>
</html>

以上就是JavaScript文档对象模型-Document类型的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn