JavaScript represents a Document by using the Document type. In the browser, the document object is an instance of HTMLDocument, indicating the entire HTML page. The Document object is an instance of the window object, so it can be accessed as a global object. Document nodes have the following features: JavaScript represents a Document by Document type. In the browser, the document object is an instance of HTMLDocument, indicating the entire HTML page. The Document object is an instance of the window object, so it can be accessed as a global object. Document nodes have the following features:
-
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 subnodes may be one DocumentType (up to one), Element (up to one), ProcessingInstruction, or Comment.
The Document type can represent HTML pages or other XML-based documents. The most common application is the document Object of the HTMLDocument instance. Through this document object, you can not only obtain page-related information, but also operate the appearance and underlying structure of the page.
Sub-nodes of the document
Although DOM standards stipulate that the child nodes of a Document node can be DocumentType, Element, ProcessingInstruction, or Comment, there are two built-in shortcuts for accessing its child nodes. The first is the documentElement attribute, which always points toElement. 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:
After the above page is parsed by the browser, its document contains only one subnode, andElement. The code for accessing this element through the documentElement attribute and the childNodes list is as follows:
// ObtainElement reference var html = document.doc umentElement; alert (html = document. childNodes [0]); // truealert (html = document. firstChild); // true
The preceding example shows that the values of documentElement, firstChild, and childNodes [0] are the same and all pointElement.
As an example of HTMLDocument, the document Object also has a body attribute, pointing directlyAttribute. Document. body is an attribute that we often use during development:
var body = document.body;
All page views support the document.doc umentElement and document. body attributes.
Another possible subnode of Document is DocumentType.A tag is a different entity from other parts of the document. You can access it through the doctype attribute.
Var doctype = document.doc type; // getReferences
Attributes and methods of the document Object
A document object is an attribute of a window object. When a window is divided into several frameworks, each framework is an attribute of the window object, and the framework itself is actually an instance of the window object. Common attributes of a document object are shown in the following table:
Some common document attributes are listed above. 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("
");for(var i=0;i"); } if(i > 0 && i%5 == 0){ document.write("
"); } document.write("
| " + attrs[i] + " | ");}document.write("
");
The above code will print the document attributes supported by the browser in alphabetical order and then move the table to the page.
In the preceding document object attributes, URL, domain, and referrer attributes are related to webpage requests. 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. If no source page exists, the referrer attribute may contain an empty string. All the information is in the HTTP Request Header, but we can use JavaScript to access them.
// Obtain the complete URL var URL = document. URL; // obtain the domain name var domain = document. domain; // obtain the URL of the Source Page. referrer = document. referrer;
Search Element
In DOM applications, the most common operation is to obtain a reference to a group of elements and then perform some operations. You can use the following methods of the document Object to retrieve elements.
-
Document. getElementById ()
-
Document. getElementsByTagName
-
Document. getElementsByName ()
The first method, document. getElementById (), receives a parameter: the ID of the element to be obtained. If this element is found, this element is returned; otherwise, null is returned. If multiple elements with the same ID exist on the page, the getElementById () method returns only the first element in the document. In IE 7 and earlier versions, if the name attribute of the form element is the same as the ID of the element to be searched, the form element will also be returned. For example:
p
When you use document. getElementById ("someId") to search for elements, IE7 willElement return. Other browsers return p elements.
Another frequently used method is document. getElementsByTagName, which searches for elements by Tag name. This method receives a parameter: the name of the tag to be searched. It returns the NodeList of zero or multiple elements. In an HTML document, this method returns an HTMLCollection object called a "dynamic" collection. For example, the following code gets all the elements on the page and returns an HTMLCollection:
var images = document.getElementByTagName("img");
Similar to NodeList, you can use square brackets or the item () method to access HTMLCollection objects:
Alert (images. length); // number of images alert (images [0]. src); // the src attribute alert (images. item (0 ). src); // the src attribute of the first image
The HTMLCollection object also has a method: namedItem (), which can be used to obtain items in the set through the name attribute of the element. For example, in the image set above, if the name attribute of an image is mypic:
You can obtain the image from the images variable using the following method:
var mypic = images.namedItem("mypic");
If you want to obtain all the elements on the page, you can use the "*" wildcard in the getElementByTagName () method to obtain them.
var allElements = document.getElementByTagName("*");
The first method to obtain elements is the special method of HTMLDocument: getElementByName (). This method returns all elements of the specified name attribute. For example, the following code:
var authors = document.getElementByName("author");
The above code returns all li elements. Similarly, the getElementByName () method returns an HTMLCollection object.
QuerySelector and querySelectorAll methods in HTML5
In addition to the above three methods for searching elements, HTML5 introduces a new document to Web APIs. querySelector and document. the querySelectorAll method is used to easily select elements from the DOM. It is similar to the jQuery selector.
The two methods use similar syntaxes and both receive a string parameter. This parameter must be a valid CSS selection syntax.
element = document.querySelector('selectors');elementList = document.querySelectorAll('selectors');
The selectors parameter can contain multiple CSS selectors separated by commas.
element = document.querySelector('selector1,selector2,...');elementList = document.querySelectorAll('selector1,selector2,...');
The two methods cannot be used to find elements with pseudo-class States. For example, querySelector (': hover') does not get the expected results.
The querySelector method returns a single element that meets the conditions. Use the CSS selector provided by the parameter to search for the DOM based on the principle of depth first and first traversal, and return the first element that meets the condition.
Element = document. querySelector ('P # iner '); // returns the first pelement = document whose id is container. querySelector ('. foo ,. bar '); // returns the first element with the foo or bar style class.
The querySelectorAll method returns all elements that meet the conditions. The result is a nodeList set. The Search rules are the same as described above.
Elements = document. querySelectorAll ('p. foo'); // returns all p with the foo class style
Note that the elements in the returned nodeList set are non-real-time (no-live). To distinguish between real-time and non-real-time returned results, see the following example:
// First select the element container = document whose id is container on the page. getElementById ('# iner'); console. log (container. childNodes. length) // The result is 2 // then add a sub-element container to it by code. appendChild (document. createElement ('P'); // This element is not only added to the page, but the variable container automatically updates the console. log (container. childNodes. length) // The result is 3.
Through the above example, we can understand what elements are updated in real time. Document. getElementById returns the real-time result. After adding a child element to it, you can obtain the number of all child elements again, it has been updated from the original two to three (Some browsers, such as Chrome, will resolve the blank space as a subnode ).
Writing of documents
A document object can write an output stream to a webpage. It has four methods: write (), writeln (), open (), and close (). The write () and writeln () methods receive a string parameter, that is, the text to be written to the output stream. The write () method is written as is, while the writeln () method adds a linefeed (\ n) at the end of the string ). You can use these two methods to dynamically add content during page loading, for example, the following code:
Document The current time is: