Document node

Overview

The document node object represents the entire document, and each web page has its own document object. The window.document property points to this object. As soon as the browser starts to load the HTML document, the object exists and can be used directly.

The document object can be obtained in different ways.

-For normal web pages, use document or window.document directly. -For web pages in the iframe frame, use the contentDocument attribute of the iframe node. -The document returned by the Ajax operation uses the responseXML attribute of the XMLHttpRequest object. -The ownerDocument property of internal nodes.

The document object inherits the EventTarget interface and the Node interface, and is mixed with the ParentNode interface. This means that the methods of these interfaces can all be called on the document object. In addition, the document object has many properties and methods of its own.

Attributes

Shortcut properties

The following properties are shortcuts to a node inside the document.

(1) document.defaultView

The document.defaultView property returns the window object to which the document object belongs. If the current document does not belong to the window object, this property returns null.

document.defaultView === window; // true

(2)document.doctype

For HTML documents, the document object generally has two child nodes. The first child node is document.doctype, which points to the <DOCTYPE> node, which is the document type (Document Type Declaration, abbreviated DTD) node. The document type node of HTML is generally written as <!DOCTYPE html>. If the webpage does not declare a DTD, this attribute returns null.

var doctype = document.doctype;
doctype; // "<!DOCTYPE html>"
doctype.name; // "html"

document.firstChild usually returns this node.

(3) document.documentElement

The document.documentElement property returns the root element node (root) of the current document. It is usually the second child node of the document node, immediately after the document.doctype node. This attribute of HTML pages is generally the <html> node.

(4) document.body, document.head

The document.body attribute points to the <body> node, and the document.head attribute points to the <head> node.

These two attributes always exist. If <head> or <body> is omitted from the source code of the webpage, the browser will create it automatically. In addition, these two attributes are writable. If you rewrite their values, it is equivalent to removing all child nodes.

(5)document.scrollingElement

The document.scrollingElement property returns the scrolling element of the document. In other words, when the document scrolls as a whole, which element is scrolling.

In standard mode, this attribute returns the root element document.documentElement (ie <html>) of the document. In compatible (quirk) mode, the <body> element is returned. If the element does not exist, null is returned.

// scroll to the top of the browser
document.scrollingElement.scrollTop = 0;

(6)document.activeElement

The document.activeElement property returns the DOM element that has the current focus. Usually, this attribute returns form elements such as <input>, <textarea>, <select>, etc. If there is no focus element currently, it returns the <body> element or null.

(7) document.fullscreenElement

The document.fullscreenElement property returns the DOM element currently displayed in fullscreen state. If it is not in full screen state, this property returns null.

if (document.fullscreenElement.nodeName == "VIDEO") {
  console.log("Play video in full screen");
}

In the above code, through document.fullscreenElement, you can know whether the <video> element is in the full screen state, so as to determine the user's behavior.

Node set attributes

The following properties return an instance of HTMLCollection, representing a collection of specific elements within the document. These collections are dynamic. Any changes to the original node will be reflected in the collection immediately.

(1)document.links

The document.links property returns all <a> and <area> nodes that have the href property set in the current document.

// Print all links in the document
var links = document.links;
for (var i = 0; i < links.length; i++) {
  console.log(links[i]);
}

(2)document.forms

The document.forms property returns all <form> form nodes.

var selectForm = document.forms[0];

The above code gets the first form of the document.

In addition to using position numbers, the id attribute and the name attribute can also be used to refer to forms.

/* HTML code is as follows
  <form name="foo" id="bar"></form>
*/
document.forms[0] === document.forms.foo; // true
document.forms.bar === document.forms.foo; // true

(3) document.images

The document.images property returns all <img> image nodes on the page.

var imglist = document.images;

for (var i = 0; i < imglist.length; i++) {
  if (imglist[i].src === "banner.gif") {
    // ...
  }
}

The above code looks for a certain picture among all img tags.

(4) document.embeds, document.plugins

The document.embeds property and the document.plugins property both return all <embed> nodes.

(5)document.scripts

The document.scripts property returns all <script> nodes.

var scripts = document.scripts;
if (scripts.length !== 0) {
  console.log("The current webpage has a script");
}

(6)document.styleSheets

The document.styleSheets property returns a collection of style sheets embedded or imported in the document. For details, please see the chapter "CSS Object Model".

(7) Summary

Except for document.styleSheets, the collection properties above all return instances of HTMLCollection.

document.links instanceof HTMLCollection; // true
document.images instanceof HTMLCollection; // true
document.forms instanceof HTMLCollection; // true
document.embeds instanceof HTMLCollection; // true
document.scripts instanceof HTMLCollection; // true

The HTMLCollection instance is an array-like object, so these attributes have the length property, and you can use the square bracket operator to refer to members. If the member has id or name attributes, you can also use the values ​​of these two attributes to refer to this member on the HTMLCollection instance.

// HTML code is as follows
// <form name="myForm">
document.myForm === document.forms.myForm; // true

Document static information attributes

The following properties return document information.

(1) document.documentURI, document.URL

Both the document.documentURI property and the document.URL property return a string representing the URL of the current document. The difference is that they inherit from different interfaces. documentURI inherits from the Document interface and can be used for all documents; URL inherits from the HTMLDocument interface and can only be used for HTML documents.

document.URL;
// http://www.example.com/about

document.documentURI === document.URL;
// true

If the document anchor (#anchor) changes, both of these attributes will change accordingly.

(2) document.domain

The document.domain property returns the domain name of the current document, excluding the protocol and port. For example, if the URL of the web page is http://www.example.com:80/hello.html, then the attribute of document.domain is equal to www.example.com. If the domain name cannot be obtained, this attribute returns null.

document.domain is basically a read-only attribute, except in one case. For web pages with secondary domain names, you can set document.domain as the corresponding upper-level domain name. For example, if the current domain name is a.sub.example.com, the document.domain property can be set to sub.example.com, or it can be set to example.com. After modification, two webpages with the same document.domain can read each other's resources, such as the set cookies.

In addition, setting document.domain will cause the port to be changed to null. Therefore, if you communicate by setting document.domain, both web pages must set this value to ensure that the ports are the same.

(3) document.location

The Location object is a native object provided by the browser and provides URL-related information and operation methods. Through the window.location and document.location properties, you can get this object.

For a detailed introduction to this object, please see the "Location Object" chapter in the "Browser Model" section.

(4) document.lastModified

The document.lastModified property returns a string that represents the last modification time of the current document. The return value of different browsers, the date format is different.

document.lastModified;
// "03/07/2018 11:18:27"

Note that the value of the document.lastModified property is a string, so it cannot be directly compared. The Date.parse method turns it into a Date instance to compare two web pages.

var lastVisitedDate = Date.parse("01/01/2018");
if (Date.parse(document.lastModified) > lastVisitedDate) {
  console.log("Webpage has been changed");
}

If there is content generated by JavaScript on the page, the document.lastModified property always returns the current time.

(5)document.title

The document.title property returns the title of the current document. By default, the value of the <title> node is returned. But the attribute is writable, once it is modified, it will return the modified value.

document.title = "New title";
document.title; // "New Title"

(6)document.characterSet

The document.characterSet property returns the encoding of the current document, such as UTF-8, ISO-8859-1 and so on.

(7)document.referrer

The document.referrer property returns a string indicating where the visitor of the current document comes from.

document.referrer;
// "https://example.com/path"

If the source cannot be obtained, or the user directly enters the URL instead of clicking on it from another webpage, document.referrer returns an empty string.

The value of document.referrer is always consistent with the Referer field of the HTTP header. However, the spelling of document.referrer has two rs, and the Referer field of the header information has only one r.

(8)document.dir

document.dir returns a string indicating the direction of the text. It has only two possible values: rtl means that the text is from right to left, and Arabic is this way; ltr means that the text is from left to right, and most texts, including English and Chinese, use this way.

(9)document.compatMode

The compatMode property returns the mode in which the browser processes the document. The possible values ​​are BackCompat (backward compatibility mode) and CSS1Compat (strict mode).

Generally speaking, if a clear DOCTYPE is set in the first line of the webpage code (such as <!doctype html>), the value of document.compatMode is always CSS1Compat.

Document status attributes

(1)document.hidden

The document.hidden property returns a boolean value indicating whether the current page is visible. If the window is minimized and the browser switches the Tab, it will cause the page to be invisible, causing document.hidden to return true.

This attribute is introduced by the Page Visibility API, and is generally used in conjunction with this API.

(2) document.visibilityState

document.visibilityState returns the visibility state of the document.

There are four possibilities for its value.

-visible: The page is visible. Note that the page may be partially visible, that is, it is not the focus window, and the front is partially blocked by other windows. -hidden: The page is not visible, it is possible that the window is minimized, or the browser is switched to another Tab. -prerender: The page is in the rendering state, and the page is not visible to the user. -unloaded: The page is unloaded from the memory.

This attribute can be used when the page is loaded to prevent certain resources from being loaded; or when the page is not visible, stop some page functions.

(3) document.readyState

The document.readyState property returns the state of the current document. There are three possible values.

-loading: HTML code loading stage (parsing has not been completed yet) -interactive: load external resources stage -complete: The loading is complete

The process of this attribute change is as follows.

  1. The browser starts to parse the HTML document, and the document.readyState attribute is equal to loading.
  2. When the browser encounters the <script> element in the HTML document and does not have the async or defer attribute, it pauses parsing and starts to execute the script. At this time, the document.readyState attribute is still equal to loading.
  3. The HTML document is parsed, and the document.readyState property becomes interactive.
  4. The browser waits for the external resources such as pictures, style sheets, font files, etc. to be loaded. Once all are loaded, the document.readyState property becomes complete.

The following code is used to check whether the web page is loaded successfully.

// basic check
if (document.readyState === "complete") {
  // ...
}

// Polling check
var interval = setInterval(function () {
  if (document.readyState === "complete") {
    clearInterval(interval);
    // ...
  }
}, 100);

In addition, every state change will trigger a readystatechange event.

The document.cookie attribute is used to manipulate browser cookies, see the "Cookie" chapter of the "Browser Model" section for details.

document.designMode

The document.designMode property controls whether the current document is editable. This attribute has only two values, on and off, and the default value is off. Once set to on, the user can edit the content of the entire document.

The following code opens the designMode property of the document inside the iframe element, and it turns it into a WYSIWYG editor.

// HTML code is as follows
// <iframe id="editor" src="about:blank"></iframe>
var editor = document.getElementById("editor");
editor.contentDocument.designMode = "on";

document.currentScript

The document.currentScript attribute is only used in the embedded script of the <script> element or the loaded external script, and returns the DOM node where the current script is located, that is, the DOM node of the <script> element.

<script id="foo">
  console.log(document.currentScript === document.getElementById("foo")); // true
</script>

In the above code, document.currentScript is the <script> element node.

document.implementation

The document.implementation property returns a DOMImplementation object. The object has three methods, mainly used to create a new Document object independent of the current document.

-DOMImplementation.createDocument(): Create an XML document. -DOMImplementation.createHTMLDocument(): Create an HTML document. -DOMImplementation.createDocumentType(): Create a DocumentType object.

The following is an example of creating an HTML document.

var doc = document.implementation.createHTMLDocument("Title");
var p = doc.createElement("p");
p.innerHTML = "hello world";
doc.body.appendChild(p);

document.replaceChild(doc.documentElement, document.documentElement);

In the above code, the first step is to generate a new HTML document doc, and then replace document.documentElement with its root element document.documentElement. This will make the contents of the current document disappear and become hello world.

Method

document.open(), document.close()

The document.open method clears all the contents of the current document and makes the document in a writable state for the document.write method to write content.

The document.close method is used to close the document opened by document.open().

document.open();
document.write("hello world");
document.close();

document.write(), document.writeln()

The document.write method is used to write content to the current document.

In the first rendering stage of the webpage, as long as the page is not closed for writing (ie, document.close() is not executed), the content written by document.write will be appended to the existing content.

// The page displays "helloworld"
document.open();
document.write("hello");
document.write("world");
document.close();

Note that document.write will be parsed as HTML code and will not be escaped.

document.write("<p>hello world</p>");

In the above code, document.write will interpret <p> as HTML tags.

If the page has been parsed (after the DOMContentLoaded event occurs), and then call the write method, it will first call the open method to erase all the contents of the current document, and then write.

document.addEventListener("DOMContentLoaded", function (event) {
  document.write("<p>Hello World!</p>");
});

// Equivalent to
document.addEventListener("DOMContentLoaded", function (event) {
  document.open();
  document.write("<p>Hello World!</p>");
  document.close();
});

If the write method is called during the page rendering process, the open method will not be called automatically. (It can be understood that the open method has been called, but the close method has not been called yet.)

<html>
  <body>
    hello
    <script type="text/javascript">
      document.write("world");
    </script>
  </body>
</html>

Open the above webpage in the browser, it will display hello world.

document.write is a method that existed before the standardization of the JavaScript language, and now there is a more standard-compliant method to write content to the document (such as assigning a value to the innerHTML attribute). Therefore, except for some special circumstances, you should try to avoid using the document.write method.

The document.writeln method is exactly the same as the write method, except that a newline character is added at the end of the output.

document.write(1);
document.write(2);
// 12

document.writeln(1);
document.writeln(2);
// 1
// 2
//

Note that the writeln method adds ASCII code line breaks, which does not work when rendered into an HTML web page, that is, line breaks are not displayed on the web page. Line breaks on the web page must be explicitly written in <br>.

document.querySelector(), document.querySelectorAll()

The document.querySelector method accepts a CSS selector as a parameter and returns the element node that matches the selector. If there are multiple nodes that meet the matching conditions, the first matching node is returned. If no matching node is found, null is returned.

var el1 = document.querySelector(".myclass");
var el2 = document.querySelector("#myParent> [ng-click]");

The document.querySelectorAll method is similar in usage to querySelector, the difference is that it returns a NodeList object that contains all the nodes that match the given selector.

elementList = document.querySelectorAll(".myclass");

The parameters of these two methods can be multiple CSS selectors separated by commas, and return the element node matching one of the selectors, which is consistent with the rules of CSS selectors.

var matches = document.querySelectorAll("div.note, div.alert");

The above code returns the div element whose class attribute is note or alert.

Both of these methods support complex CSS selectors.

// Select the element whose data-foo-bar attribute is equal to someval
document.querySelectorAll('[data-foo-bar="someval"]');

// Select all the elements that fail validation in the myForm form
document.querySelectorAll("#myForm :invalid");

// Select div elements, except those whose class contains ignore
document.querySelectorAll("DIV:not(.ignore)");

// Select div, a, script three types of elements at the same time
document.querySelectorAll("DIV, A, SCRIPT");

However, they do not support CSS pseudo element selectors (such as :first-line and :first-letter) and pseudo-type selectors (such as :link and :visited), that is, they cannot be selected. Elements and pseudo-classes.

If the parameter of the querySelectorAll method is the string *, all element nodes in the document will be returned. In addition, the return result of querySelectorAll is not a dynamic collection, and will not reflect the changes of element nodes in real time.

Finally, these two methods are not only defined on the document object, but also defined on the element node, that is, they can also be called on the element node.

document.getElementsByTagName()

The document.getElementsByTagName() method searches for the HTML tag name and returns the elements that meet the conditions. Its return value is an array-like object (HTMLCollection instance), which can reflect the changes of HTML documents in real time. If there are no matching elements, an empty set is returned.

var paras = document.getElementsByTagName("p");
paras instanceof HTMLCollection; // true

The above code returns all the p element nodes of the current document.

HTML tag names are case-insensitive, so the parameters of the getElementsByTagName() method are also case-insensitive. In addition, in the returned result, the order of each member is the order in which they appear in the document.

If you pass in *, you can return all HTML elements in the document.

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

Note that the element node itself also defines the getElementsByTagName method, which returns the eligible elements among the descendant elements of the element. In other words, this method can be called not only on the document object, but also on any element node.

var firstPara = document.getElementsByTagName("p")[0];
var spans = firstPara.getElementsByTagName("span");

The above code selects all the span elements inside the first p element.

document.getElementsByClassName()

The document.getElementsByClassName() method returns an array-like object (HTMLCollection instance), including all elements whose class names meet the specified conditions, and the changes of the elements are reflected in the return result in real time.

var elements = document.getElementsByClassName(names);

Because class is a reserved word, JavaScript always uses className to represent the class of CSS.

The parameter can be multiple class, separated by spaces.

var elements = document.getElementsByClassName("foo bar");

The above code returns elements with both class, foo and bar, and the order of foo and bar is not important.

Note that in normal mode, CSS class is case sensitive. (Under quirks mode, case is not sensitive.)

Like the getElementsByTagName() method, the getElementsByClassName() method can be called not only on the document object, but also on any element node.

// Called on non-document objects
var elements = rootElement.getElementsByClassName(names);

document.getElementsByName()

The document.getElementsByName() method is used to select HTML elements with the name attribute (such as <form>, <radio>, <img>, <frame>, <embed> And <object> etc.), return an array-like object (NodeList instance), because there may be more than one element with the same name attribute.

// The form is <form name="x"></form>
var forms = document.getElementsByName("x");
forms[0].tagName; // "FORM"

document.getElementById()

The document.getElementById() method returns the element node that matches the specified id attribute. If no matching node is found, null is returned.

var elem = document.getElementById("para1");

Note that the parameters of this method are case sensitive. For example, if the id attribute of a certain node is main, then document.getElementById('Main') will return null.

Both the document.getElementById() method and the document.querySelector() method can obtain element nodes. The difference is that the parameters of the document.querySelector() method use CSS selector syntax, document.getElementById() The parameter of the method is the id attribute of the element.

document.getElementById("myElement");
document.querySelector("#myElement");

In the above code, both methods can select the element with id as myElement, but document.getElementById() is much more efficient than document.querySelector().

In addition, this method can only be used on the document object, not on other element nodes.

document.elementFromPoint(), document.elementsFromPoint()

The document.elementFromPoint() method returns the element node at the top of the specified position on the page.

var element = document.elementFromPoint(50, 50);

The above code selects the uppermost HTML element at the coordinate position of (50, 50).

The two parameters of the elementFromPoint method are the abscissa and ordinate relative to the upper left corner of the current viewport in order, in pixels. If the HTML element at that position is not returnable (such as the scroll bar of a text box), then its parent element (such as a text box) is returned. If the coordinate value is meaningless (for example, a negative value or exceeds the size of the viewport), null is returned.

document.elementsFromPoint() returns an array, the members are all the elements at the specified coordinates (relative to the viewport).

var elements = document.elementsFromPoint(x, y);

document.createElement()

The document.createElement method is used to generate an element node and return the node.

var newDiv = document.createElement("div");

The parameter of the createElement method is the tag name of the element, that is, the tagName attribute of the element node, which is not sensitive to the case of HTML pages, that is, the parameter is div or DIV and returns the same kind of node. If the parameter contains angle brackets (ie < and >), an error will be reported.

document.createElement("<div>");
// DOMException: The tag name provided ('<div>') is not a valid name

Note that the parameter of document.createElement can be a custom tag name.

document.createElement("foo");

document.createTextNode()

The document.createTextNode method is used to generate a text node (Text instance) and return the node. Its parameter is the content of the text node.

var newDiv = document.createElement("div");
var newContent = document.createTextNode("Hello");
newDiv.appendChild(newContent);

The above code creates a div node and a text node, and then inserts the text node into the div node.

This method can ensure that the returned node is rendered as text by the browser, not as HTML code. Therefore, it can be used to display user input and avoid XSS attacks.

var div = document.createElement("div");
div.appendChild(document.createTextNode("<span>Foo & bar</span>"));
console.log(div.innerHTML);
// <span>Foo & bar</span>

In the above code, the createTextNode method escapes the greater than and less than signs to ensure that even if the content entered by the user contains malicious code, it can be displayed correctly.

It should be noted that this method does not escape single and double quotes, so it cannot be used to assign values ​​to HTML attributes.

function escapeHtml(str) {
  var div = document.createElement('div');
  div.appendChild(document.createTextNode(str));
  return div.innerHTML;
};

var userWebsite ='" onmouseover="alert(\'derp\')" "';
var profileLink ='<a href="' + escapeHtml(userWebsite) +'">Bob</a>';
var div = document.getElementById('target');
div.innerHTML = profileLink;
// <a href="" onmouseover="alert('derp')" "">Bob</a>

In the above code, because the createTextNode method does not escape the double quotes, the onmouseover method is injected with code.

document.createAttribute()

The document.createAttribute method generates a new attribute node (an instance of Attr) and returns it.

var attribute = document.createAttribute(name);

The parameter name of the document.createAttribute method is the name of the attribute.

var node = document.getElementById("div1");

var a = document.createAttribute("my_attrib");
a.value = "newVal";

node.setAttributeNode(a);
// or
node.setAttribute("my_attrib", "newVal");

The above code is the div1 node, insert a my_attrib attribute with a value of newVal.

document.createComment()

The document.createComment method generates a new comment node and returns the node.

var CommentNode = document.createComment(data);

The parameter of the document.createComment method is a string, which will become the content of the comment node.

document.createDocumentFragment()

The document.createDocumentFragment method generates an empty document fragment object (DocumentFragment instance).

var docFragment = document.createDocumentFragment();

DocumentFragment is a DOM fragment that exists in memory and is not part of the current document. It is often used to generate a more complex DOM structure and then insert it into the current document. The advantage of this is that because DocumentFragment does not belong to the current document, any changes to it will not trigger the re-rendering of the web page, which has better performance than directly modifying the DOM of the current document.

var docfrag = document.createDocumentFragment();

[1, 2, 3, 4].forEach(function (e) {
  var li = document.createElement("li");
  li.textContent = e;
  docfrag.appendChild(li);
});

var element = document.getElementById("ul");
element.appendChild(docfrag);

In the above code, the document fragment docfrag contains four <li> nodes, and these child nodes are inserted into the current document at one time.

document.createEvent()

The document.createEvent method generates an event object (an instance of Event), which can be used by the element.dispatchEvent method to trigger a specified event.

var event = document.createEvent(type);

The parameter of the document.createEvent method is the event type, such as UIEvents, MouseEvents, MutationEvents, and HTMLEvents.

var event = document.createEvent("Event");
event.initEvent("build", true, true);
document.addEventListener(
  "build",
  function (e) {
    console.log(e.type); // "build"
  },
  false
);
document.dispatchEvent(event);

The above code creates a new event instance named build, and then triggers the event.

document.addEventListener(), document.removeEventListener(), document.dispatchEvent()

These three methods are used to handle events of the document node. They all inherit from the EventTarget interface. For details, please refer to the chapter "EventTarget Interface".

// Add event listener function
document.addEventListener("click", listener, false);

// Remove event listener function
document.removeEventListener("click", listener, false);

// trigger event
var event = new Event("click");
document.dispatchEvent(event);

document.hasFocus()

The document.hasFocus method returns a boolean value indicating whether any element in the current document is activated or has the focus.

var focused = document.hasFocus();

Note that the document with focus must be activated (active), otherwise it is not true, the activated document may not have focus. For example, when the user clicks a button, a new window pops up from the current window. The new window is active but does not have the focus.

document.adoptNode(), document.importNode()

The document.adoptNode method removes a node and its child nodes from the original document or DocumentFragment, belongs to the current document object, and returns the inserted new node. The ownerDocument property of the inserted node object will become the current document object, and the parentNode property will be null.

var node = document.adoptNode(externalNode);
document.appendChild(node);

Note that the document.adoptNode method only changes the attribution of the node, and does not insert the node into the new document tree. Therefore, you need to use the appendChild method or the insertBefore method to insert the new node into the current document tree.

The document.importNode method is to copy a node and its child nodes from the original document or DocumentFragment, and make them belong to the current document object. The ownerDocument property of the copied node object will become the current document object, and the parentNode property will be null.

var node = document.importNode(externalNode, deep);

The first parameter of the document.importNode method is an external node, and the second parameter is a boolean value indicating whether the external node is a deep copy or a shallow copy. The default is shallow copy (false). Although the second parameter is optional, it is recommended to always keep this parameter and set it to true.

Note that the document.importNode method just copies the external node, at this time the parent node of the node is null. The next step must also be to insert this node into the current document tree.

var iframe = document.getElementsByTagName("iframe")[0];
var oldNode = iframe.contentWindow.document.getElementById("myNode");
var newNode = document.importNode(oldNode, true);
document.getElementById("container").appendChild(newNode);

The above code copies a specified node myNode from the iframe window and inserts the current document.

document.createNodeIterator()

The document.createNodeIterator method returns a child node iterator.

var nodeIterator = document.createNodeIterator(
  document.body,
  NodeFilter.SHOW_ELEMENT
);

The above code returns the iterator of the child nodes of the <body> element.

The first parameter of the document.createNodeIterator method is the root node to be traversed, and the second parameter is the type of node to be traversed, which is designated as the element node (NodeFilter.SHOW_ELEMENT). Several main node types are written as follows.

-All nodes: NodeFilter.SHOW_ALL -Element node: NodeFilter.SHOW_ELEMENT -Text node: NodeFilter.SHOW_TEXT -Comment node: NodeFilter.SHOW_COMMENT

The document.createNodeIterator method returns a "traverser" object (NodeFilter instance). The nextNode() method and previousNode() method of this instance can be used to traverse all child nodes.

var nodeIterator = document.createNodeIterator(document.body);
var pars = [];
var currentNode;

while ((currentNode = nodeIterator.nextNode())) {
  pars.push(currentNode);
}

In the above code, the nextNode method of the traverser is used to read all the child nodes of the root node into an array in turn. The nextNode method first returns the node where the internal pointer of the traverser is located, and then moves the pointer to the next node. After all members are traversed, null is returned. The previousNode method first moves the pointer to a node, and then returns to that node.

var nodeIterator = document.createNodeIterator(
  document.body,
  NodeFilter.SHOW_ELEMENT
);

var currentNode = nodeIterator.nextNode();
var previousNode = nodeIterator.previousNode();

currentNode === previousNode; // true

In the above code, both currentNode and previousNode point to the same node.

Note that the first node returned by the traverser is always the root node.

pars[0] === document.body; // true

document.createTreeWalker()

The document.createTreeWalker method returns a DOM subtree walker. It is basically similar to the document.createNodeIterator method, the difference is that it returns a TreeWalker instance, which returns a NodeIterator instance. In addition, its first node is not the root node.

The first parameter of the document.createTreeWalker method is the root node to be traversed, and the second parameter specifies the type of node to be traversed (the same as the second parameter of the document.createNodeIterator method).

var treeWalker = document.createTreeWalker(
  document.body,
  NodeFilter.SHOW_ELEMENT
);

var nodeList = [];

while (treeWalker.nextNode()) {
  nodeList.push(treeWalker.currentNode);
}

The above code traverses all the element nodes under the <body> node and inserts them into the nodeList array.

document.execCommand(), document.queryCommandSupported(), document.queryCommandEnabled()

(1) document.execCommand()

If the document.designMode property is set to on, then the entire document can be edited by the user; if the element's contenteditable property is set to true, then the element is editable. In both cases, you can use the document.execCommand() method to change the style of the content. For example, document.execCommand('bold') will make the font bold.

document.execCommand(command, showDefaultUI, input);

The method accepts three parameters.

-command: A string indicating the style to be implemented. -showDefaultUI: Boolean value, indicating whether to use the default user interface, it is recommended to always set it to false. -input: A string representing the auxiliary content of the style. For example, when generating a hyperlink, this parameter is the URL to be linked. If the second parameter is set to true, the browser will pop up a prompt box, asking the user to enter the parameter in the prompt box. However, not all browsers support this. For compatibility, you still need to deploy your own way to obtain this parameter.

var url = window.prompt("Please enter the URL");

if (url) {
  document.execCommand("createlink", false, url);
}

In the above code, first prompt the user to enter the URL to be linked, and then manually generate the hyperlink. Note that the second parameter is false, which means there is no need to automatically pop up a prompt box at this time.

The return value of document.execCommand() is a boolean value. If it is false, it means that this method cannot take effect.

In most cases, this method only takes effect on the selected content. If there are multiple content editable areas, only the element with the current focus will take effect.

There are many style changes that the document.execCommand() method can perform. Here are some of them: bold, insertLineBreak, selectAll, createLink, insertOrderedList, subscript, delete, insertUnorderedList, superscript, formatBlock, insertParagraph, undo, forwardDelete, insertText , Unlink, insertImage, italic, unselect, insertHTML, redo. These values ​​can be used as the first parameter, and their meaning is not difficult to see literally.

(2) document.queryCommandSupported()

The document.queryCommandSupported() method returns a boolean value indicating whether the browser supports a certain command of document.execCommand().

if (document.queryCommandSupported("SelectAll")) {
  console.log(
    "The browser supports all the contents of the selected editable area"
  );
}

(3) document.queryCommandEnabled()

The document.queryCommandEnabled() method returns a boolean value indicating whether a certain command of document.execCommand() is currently available. For example, the bold (bold) command is only available when there is text selected, and if no text is selected, it is not available.

// HTML code is
// <input type="button" value="Copy" onclick="doCopy()">

function doCopy() {
  // Does the browser support the copy command (copy the selected content to the clipboard)
  if (document.queryCommandSupported("copy")) {
    copyText("Hello");
  } else {
    console.log("Browser does not support");
  }
}

function copyText(text) {
  var input = document.createElement("textarea");
  document.body.appendChild(input);
  input.value = text;
  input.focus();
  input.select();

  // Whether there is currently selected text
  if (document.queryCommandEnabled("copy")) {
    var success = document.execCommand("copy");
    input.remove();
    console.log("Copy Ok");
  } else {
    console.log("queryCommandEnabled is false");
  }
}

In the above code, first determine whether the browser supports the copy command (allowing the selected content in the editable area to be copied to the clipboard). If it does, create a temporary text box with the content "Hello" and add Its selected. Then, judge whether the selection is successful, if successful, copy "Hello" to the clipboard, and then delete the temporary text box.

document.getSelection()

This method points to window.getSelection(), see the introduction in the section of window object.