Document Object Model DOM
The document Object Model (DOM) is the basic API for representing and manipulating the content of HTML and XML documents. DOM tree: The tree structure of AN HTML document contains elements that represent HTML tags or elements such as,
) and a node that represents a text string.
The tree structure of HTML can be described very well by using family atlas
- The immediate node above a node is its parent
- The immediate nodes at the next level are their children
- Nodes with the same parent at the same level are siblings
- The set of nodes at all levels below a node is its descendant node
- The parent node of a node and all nodes above it are the ancestor nodes
The node node
Each node represents a Node object
-
Document: At the root of the tree is the Document node, which represents the entire Document.
-
Element: The node of an HTML Element is an Element node.
-
Text: The node representing the Text is the Text node.
Selecting document elements
Most client-side JavaScript programs always run on one or more document elements. When these programs start, the global variable document can be used to reference the Document object. In order to manipulate the elements in the document, we must somehow select the elements
Select elements by ID
Any HTML element can have an ID attribute, which must be unique within the document. You can use the Document object’s getElementById() method to select an ID-based element.
var logo = document.getElementById();
Copy the code
Select elements by name
The NAME attribute of HTML is originally intended to assign names to form elements and use the value of the attribute when the form data is submitted to the server. Like the ID attribute, the name attribute assigns a name to an element, but unlike ID, the value of the name attribute does not have to be unique.
var newsList = document.getElementByName("news");
Copy the code
Returns an array of NodeList objects
Select elements by tag name
The Document object’s getElementsByTagName() method can be used to select all HTML elements of the specified type (tag name).
var pList = document.getElementsByTagName("p");
Copy the code
Type getElementByName(), getElementsByTagName() returns an array of NodeList objects.
Select elements from CSS classes
Select groups of document elements based on identifiers in the class attribute values.
var cats = document.getElementsByClassName("cat");
Copy the code
GetElementsByclassName () returns a real-time array of NodeList objects
Select elements using CSS selectors
CSS selectors can be used to accurately describe several or more groups of elements in a document. We can also get an HTML element or a set of HTML elements using the syntax rules of the CSS selector.
The Document methods querySelectorAll() and querySelector(), which take a string argument to a CSS selector.
var newsList = document.querySelectorAll(".news");
Copy the code
The array of NodeList objects returned by the querySelectorAll() method is not real-time: it contains elements matched by the selector at the time of invocation, but it does not update subsequent document changes.
Unlike querySelectorAll(), querySelector(), which returns the first matched element and returns null if there is no matched element
Document structure and traversal
Once an element is selected from the document, sometimes you need to look up the parts of the document that are structurally relevant to it (father, brother, and child). The node type defines the attributes needed to traverse the tree.
Documents as a tree of nodes
The Document object, its Element object, and the Text object representing Text in the Document are Node objects. Node defines the following attributes:
-
ParentNode, the parent of this node, or for document-like objects should be null because it has no parent.
-
ChildNodes, read-only array-like objects (NodeList objects) that are real-time representations of the node’s children.
-
FirstChild, lastChild, the first and last of the node’s children, or null if the node has no children.
-
NextSibling, previousSibling, the first and nextSibling of the node. Two nodes that have the same parent node are siblings. The order of nodes reflects the order in which they appear in the document.
-
NodeType: indicates the type of the node: 9 represents the Document node, 1 represents the Element node, 3 represents the Text node, 8 represents the Comment node, and 11 represents the DocumentFragemnt node.
-
NodeValue, Text node or Comment node Text content.
-
NodeName, the label name of the element, in uppercase.
Document as element tree
When the main point of interest is on the elements in the document rather than the text between them, there is another API that is more useful. It treats the document as a tree of Element objects.
attribute
HTML elements consist of a tag and a set of name/value pairs called attributes. The attribute values of HTML elements are available in the property of the HTMLElement object that represents those elements.
HTML attributes as Element attributes
The HTMLElement object that represents the elements of an HTML document defines read/write attributes that map the HTML attributes of the element. For example, to query the URL of a picture, you can use representationThe SRC attribute of the HTMLElement object:
var image = document.getElementById("logo");
var logoUrl = image.src; // The SRC attribute is the URL of the image
Copy the code
Again, it can be one
var form = document.forms[0]; // The first form in the document
form.action = "http://www.baidu.com";
form.method = "GET";
Copy the code
Some HTML attribute names are reserved words in JavaScript. For these attributes, the general rule is to prefix the attribute name with “HTML”. For example, The exception is that the for attribute in HTML (the lable element) becomes the htmlFor. Class attribute in JavaScript, which becomes classname in JavaScript.
var lable = document.getElementsByTagName("lable") [0];
lable.htmlFor === "name";
lable.classname = "form-name";
Copy the code
Gets and sets non-standard HTML attributes
The Element type also defines the getAttribute() and setAttribute() methods to query and set non-standard HTML attributes.
var image = document.images[0];
var width = parseInt(image.getAttribute("width"));
Copy the code
For HTML elements, attribute names are case insensitive
The Element type also defines two related methods, hasAttribute() and removeAttribute(), which detect the presence of named attributes and remove them completely.
Data set attributes
In HTML5, any lowercase attribute name prefixed with “data-” is legal. These “dataset attributes” have no effect on the performance of their elements, and they define a standard way to attach additional data without compromising document legitimacy.
HTML5 also defines the dataset property on an Element object. This property refers to an object whose individual properties correspond to the data- property with the prefix removed. The hyphenated attribute corresponds to the hump naming attribute name: the data-name-a attribute becomes the dataset. NameA attribute.
As an attribute of the Attr node
For an Element object, the Attributes attribute is a read-only array-like object that represents all the attributes of the Element. The Attributes object is real-time.
document.body.attributes[0]; // the first attribute of the element
document.body.attributes.bgcolor // element's background property
document.body.attributes["onload"] // the onload attribute of the element
Copy the code
Content of the element
- The content is an HTML string
- The content is a plain text string
- The contents are a Text node, an Elemnt node containing a Text child node, and another Text node.
Element content as HTML
Read the innerHTML attribute of an Element as a string tag to return the content of that Element. Setting this property on the element invokes the Web browser’s parser to replace the element’s current content with a parsed representation of the new string content. Web browsers are very good at parsing HTML, and setting innerHTML is usually very efficient, even when the specified value needs to be parsed. Note, however, that adding a piece of innerHTML property repeatedly with the “+=” operator is often inefficient because it has to be serialized and parsed.
Element content as plain text
Sometimes you need to query element content in plain text, or insert plain text into a document without translating Angle brackets and ampersands used in HTML tags. The standard way to do this is to use the Node textContent property:
var para = document.getElementByTagName("p") [0];
var text = para.textContent;
para.textContent = "have a good time!";
Copy the code
Element content as a Text node
When you think about the content of an element, you’re usually interested in its Text node.
Create, insert, and delete nodes
The Document type defines methods for creating Element and Text objects, and the Node type defines methods for inserting, deleting, and replacing nodes in a tree.
Create a node
New Element nodes can be created using the createElement() method of the Document object. Pass the label name to the method.
var newElement = document.createElement("DIV"); // HTML is case insensitive
Copy the code
The Text node is created in a similar way:
var newNode = document.createTextNode("text node content");
Copy the code
Copy an existing node. Each node has a cloneNode() method that returns a brand new copy of the node:
var div = document.getElementsByTagName("div") [0];
div.cloneNode(); // Shallow replication by default
div.cloneNode(true); // Pass true to recursively copy all descendant children
Copy the code
Insert the node
-
The appendChild() method is called on the Elemnet node that needs to be inserted and inserts the specified node as the last child of that node.
-
The insertBefore() method takes two arguments, the first is a new node with an insert and the second is an existing node that is inserted before the new node. If null is passed as the second argument,insertBefore() behaves like appendChild().
Delete and replace nodes
- The removeChild() method removes a node from the document tree. Instead of being called on the node to be deleted, it deletes the child nodes of that node.
Suppose n node is deleted:
n.parentNode.removeChild(n);
Copy the code
- The replaceChild() method removes a child node and replaces it with a new one.
n.parentNode.replaceChild(document.createTextNode("hello"), n);
Copy the code
Using DocumentFragment
A DocumentFragment is a special type of Node that acts as a temporary container for other nodes. The special aspect of a DocumentFragment is that it causes a set of nodes to be treated as one node: If you pass a DocumentFragment into appendChild(), insertBefore(), or replaceChild(), you are inserting all the children of the DocumentFragment into the document, not the fragment itself. Compared with Document, the biggest difference is that DocumentFragment is not part of the real DOM tree, and its change will not trigger the DOM tree re-rendering, and will not cause performance problems.
DocumentFragment application (MDN) :
const list = document.querySelector('#list');
const fruits = ['Apple'.'Orange'.'Banana'.'Melon'];
const fragment = document.createDocumentFragment();
fruits.forEach(fruit= > {
const li = document.createElement('li');
li.innerHTML = fruit;
fragment.appendChild(li);
});
list.appendChild(fragment);
Copy the code