JavaScript Day10 DOM Detailed Explanation

DOM

DOM is the interface for JS to operate web pages, and its full name is "Document Object Model". Its function is to convert a web page into a JS object, so that various operations (such as adding and deleting content) can be performed with scripts.

Documentation

The document represents the entire HTML web document

object

Object representation converts each part of the web page into an object.

model

Use the model to represent the relationship between objects, which is convenient for us to obtain objects

The Document Object Model (DOM) is the programming interface for web pages. It provides a structured representation of the document (structure tree) and defines a way - programs can access the structure tree to change the structure, style and content of the document.

DOM provides a representation of documents as a structured set of nodes and objects containing properties and methods . Essentially, it connects web pages to scripting or programming languages.

To change something on the page, JS needs access to all elements in the page. This entry, along with methods and properties for adding, moving, changing, or removing HTML elements, is obtained through the DOM.

The browser will parse structured documents (such as HTML and XML) into a series of nodes according to the DOM model, and then form a tree structure (DOM Tree) from these nodes. All nodes and the final tree structure have standardized external interfaces. Therefore, DOM can be understood as a programming interface of a web page . DOM has its own international standards, and the current general versions are DOM 3 and DOM 4.

Strictly speaking, DOM does not belong to JS, but manipulating DOM is the most common task of JS, and JS is also the language most commonly used for DOM manipulation. DOM is the api provided by browser manufacturers for js to operate html. Different browser manufacturers may provide different apis, so dom has compatibility problems (a small part)

1. Node level

​ Any HTML or XML document can be represented by DOM as a hierarchy of nodes. There are many types of nodes, and each type corresponds to different information and (or) tags in the document, and also has its own different characteristics, data, and methods, and has certain relationships with other types. These relationships form a hierarchy, allowing markup to be represented as a tree structure rooted at a particular node. Take the following HTML as an example:

<html>
<head>
  <title>Sample Page</title>
</head>
<body>
  <p>Hello World!</p>
</body>
</html>

insert image description here

Among them, the document node represents the root node of each document. Here, the only child node of the root node is the element, which we call the document element (documentElement). The document element is the outermost element of the document, and all other elements exist within this element. Each document can have only one document element. In an HTML page, a document element is always an element. In XML documents, there is no such predefined element, and any element may become a document element. Each piece of markup in HTML can be represented as a node in this tree structure. Element nodes represent HTML elements, attribute nodes represent attributes, document type nodes represent document types, and comment nodes represent comments. There are a total of 12 node types in the DOM, which all inherit from a base type.

1.2. Nodes

The smallest unit of DOM is called a node . The tree structure (DOM tree) of the document is composed of various types of nodes. Each node can be regarded as a leaf of the document tree.

There are seven types of nodes: Document, DocumentType, Element, Text, Comment, DocumentFragment.

  • common node
    Document node (document)

    ​ The document object of the entire HTML document exists as a property of the window object, and we can use it directly without obtaining it.

    Element node (Element)

    HTML tags in HTML documents.

    Attribute node (Attribute)

    ​ The attributes of an element represent the attributes of each tag. It should be noted here that the attribute node is not a child node of the element node, but a part of the element node.

    Text node (Text)

    ​ Text content in HTML tags.

  • other nodes
    DocumentType

    ​ doctype tag (eg <!DOCTYPE html>).

    Comment

    ​ Notes

    DocumentFragment

    ​ document fragment

These seven kinds of nodes are all derived objects of the node object provided by the browser (the Node object to be discussed below), and have some common properties and methods.

1.3. Node tree

All nodes of a document can be abstracted into a tree structure according to their level. This tree structure is the DOM.

insert image description here

The topmost node is documentthe node, which represents the entire document. The highest HTML tag in the document, generally <html>, it constitutes the root node (root node) of the tree structure, and other HTML tag nodes are its subordinates.

In addition to the root node, other nodes have three relationships with the surrounding nodes.

  • Parent node relationship (parentNode): the direct superior node.

  • Child node relationship (childNode): the direct subordinate node.

  • Sibling node relationship (sibling): nodes that have the same parent node.

DOM provides an operation interface to obtain the nodes of the three relationships. Among them, the child node interface includes attributes such as firstChild(the first child node) and (the last child node), and the sibling node interface includes (the next sibling node) and (the next sibling node) attributes .lastChildnextSiblingpreviousSibling

2. Node type

DOM Level 1 describes an interface called Node that all DOM node types must implement. The Node interface is implemented in JavaScript as the Node type, which is directly accessible in all browsers except IE. In JavaScript, all node types inherit from the Node type, so all types share the same basic properties and methods.

2.1. Properties

2.1.1.nodeType

The nodeType attribute returns an integer value, indicating the type of the node. The commonly used node types are as follows

node type value corresponding constant
Document node (document) 9 Node.DOCUMENT_NODE
element node 1 Node.ELEMENT_NODE
attribute node (attr) 2 Node.ATTRIBUTE_NODE
text node (text) 3 Node.TEXT_NODE
Document Type Node (DocumentType) 10 Node.DOCUMENT_TYPE_NODE
Comment node (Comment) 8 Node.COMMENT_NODE
Document fragment node (DocumentFragment) 11 Node.DOCUMENT_FRAGMENT_NODE
<script>
  console.log(document.nodeType); //9
</script>
2.1.2.nodeName

The nodeName property returns the name of the node

<div id="d1">hello world</div>
<script>
  var div = document.getElementById('d1');
  console.log(div.nodeName); //DIV
</script>
2.1.3.nodeValue

The nodeValue property returns a string representing the text value of the current node itself. This property can be read and written only text nodes (text), comment nodes (comment) and attribute nodes (attr) have text values.

<div id="d1">hello world</div>
<script>
  var div = document.getElementById('d1');
  console.log(div.nodeValue); // null
  // 读
  console.log(div.firstChild.nodeValue); //hello world
  // 写
  div.firstChild.nodeValue = '123';
</script>
2.1.4.textContent

The textContent property returns the text content of the current node and all its descendant nodes

<div id="d1">Hello <span>JavaScript</span> DOM</div>
<script>
  var div = document.getElementById('d1');
  console.log(div.textContent); //Hello JavaScript DOM
</script>
2.1.5.nextSibling

The nextSibling property returns the first sibling node immediately following the current node. Returns null if there are no sibling nodes behind the current node

( Note : Text nodes such as "space" or "carriage return" may be obtained)

<div id="d1">hello</div><div id="d2">world</div>
<script>
  var div1 = document.getElementById('d1');
  var div2 = document.getElementById('d2');
  console.log(div1.nextSibling); //<div id="d2">world</div>
  console.log(div1.nextSibling === div2); // true
</script>
2.1.6.previousSibling

The previousSibling property returns the closest sibling node in front of the current node. Returns null if the current node has no previous sibling nodes

<div id="d1">hello</div><div id="d2">world</div>
<script>
  var div1 = document.getElementById('d1');
  var div2 = document.getElementById('d2');
  console.log(div2.previousSibling); //<div id="d1">hello</div>
  console.log(div2.previousSibling === div1); // true
</script>
2.1.7.parentNode

The parentNode property returns the parent node of the current node. For a node, its parent node can only be of three types: element node (element), document node (document) and document fragment node (documentfragment)

<div id="d1">hello world</div>
<script>
  var div1 = document.getElementById('d1');
  console.log(div1.parentNode); // body
</script>
2.1.8.parentElement

The parentElement property returns the parent element node of the current node. If the current node has no parent node, or the parent node type is not an element node, return null

<div id="d1">hello world</div>
<script>
  var div1 = document.getElementById('d1');
  console.log(div1.parentElement); // body
  // 将父元素节点的背景颜色设置为红色
  div1.parentElement.style.backgroundColor = 'red';
</script>
2.1.9.firstChild和lastChild

The firstChild property returns the first child node of the current node, or null if the current node has no child nodes, and last returns the last child node.

<div id="d1">hello world<div>我是子节点</div></div>
<div id="d2"><div>我是子节点</div></div>
<script>
  var div1 = document.getElementById('d1');
  console.log(div1.firstChild); // hello world
  console.log(div1.lastChild); // <div>我是子节点</div>
  var div2 = document.getElementById('d2');
  console.log(div2.firstChild); // <div>我是子节点</div>
</script>
2.1.10.childNodes

The childNodes property returns an array-like object (NodeList collection), whose members include all child nodes of the current node

<div id="d1">hello world<div>我是子节点</div></div>
<script>
  var div1 = document.getElementById('d1');
  console.log(div1.childNodes); //NodeList[text, div]
</script>

We can also use a for loop to traverse all child nodes of a node

var div = document.getElementById('div1');
var children = div.childNodes;
for (var i = 0; i < children.length; i++) {
  // ...
}

2.2. Method

The following methods are commonly used methods for operating nodes, and the most commonly used method is appendChild(), which is used to add nodes at the end of the childNodes list.

Note: The following four methods require the parent node object to call!
2.2.1.appendChild

The appendChild method accepts a node object as a parameter and inserts it into the current node as the last child node. The return value of this method is the child node of the inserted document.

<script>
  // 创建元素节点p
  var p = document.createElement('p');
  // 向p标签插入内容
  p.innerHTML = '我是一个p标签';
  // 将节点插入到body中
  document.body.appendChild(p);
</script>
2.2.2.insertBefore()

The insertBefore method is used to insert a node into a specified position inside the parent node.

var insertedNode = parentNode.insertBefore(newNode, referenceNode);

The insertBefore method accepts two parameters, the first parameter is the node newNode to be inserted, and the second parameter is a child node referenceNode inside the parent node parentNode. newNode will be inserted in front of the child node referenceNode. The return value is the inserted new node newNode

<div id="parentElement">
  <span id="childElement">foo bar</span>
</div>
<script>
  //创建一个新的、普通的<span>元素
  var sp1 = document.createElement("span");
  // 向span标签插入内容
  sp1.innerHTML = '我是span标签'
  //插入节点之前,要获得节点的引用
  var sp2 = document.getElementById("childElement");
  //获得父节点的引用
  var parentDiv = sp2.parentNode;
  //在DOM中在sp2之前插入一个新元素
  parentDiv.insertBefore(sp1, sp2);
</script>
2.2.3.removeChild()

The removeChild method accepts a child node as a parameter, which is used to remove the child node from the current node. The return value is the removed child node.

<div id="d1">
  <span id="s1">我是span标签</span>
</div>
<script>
  var span1 = document.getElementById('s1');
  span1.parentNode.removeChild(span1);
</script>
2.2.4.replaceChild()

The replaceChild method is used to replace a child node of the current node with a new node.

var replacedNode = parentNode.replaceChild(newChild, oldChild);

The replaceChild method accepts two parameters. The first parameter newChild is the new node to be replaced, and the second parameter oldChild is the child node to be replaced. The return value is the node oldChild that was replaced.

<div id="d1">
  <span id="s1">我是span标签</span>
</div>
<script>
  var span1 = document.getElementById('s1');
  //创建一个新的div标签
  var div1 = document.createElement("div");
  // 向div标签插入内容
  div1.innerHTML = '我是div1标签';
  // 节点替换
  span1.parentNode.replaceChild(div1, span1);
</script>
2.2.5. Other methods
cloneNode()

method returns a copy of the node on which the method was called.

var dupNode = node.cloneNode(deep);

node

the node to be cloned

dupNode

Replica node generated by cloning

deep optional

Whether to use deep cloning, if true, all descendant nodes of this node will also be cloned, if false, only the node itself will be cloned.

var p = document.getElementById("para1"),
var p_prime = p.cloneNode(true);

3. Document type

Javascript represents documents by using the Document type. In the browser, the document object is an instance of HTMLDocument, representing the entire HTML page. The document object is a property of the window object, so it can be called directly. HTMLDocument inherits from Document.

3.1. Properties

documentElement

​ always points to an element in the HTML page.

body

​ point directly to the element

doctype

​ Access to <!DOCTYPE>, browser support is inconsistent, rarely used

title

​ Get the title of the document

URL

​ Get the full URL

domain

​ Obtain a domain name and set it up, which is often used in cross-domain access.

referrer

​ Get the URL of the page linked to the current page, that is, the URL of the source page.

images

​ Get all img objects and return an HTMLCollection class array object

forms

​ Get all form objects and return an HTMLCollection-like array object

links

​ Get all elements with href attribute in the document

3.2. DOM programming interface

The HTML DOM can be accessed through JavaScript (and other programming languages ​​as well).

In the DOM, all HTML elements are defined as objects .

The programming interface is the properties and methods of each object.

Attributes are values ​​that you can get or set (such as changing the content of an HTML element).

Methods are actions you can perform (such as adding or removing HTML elements).

example

The following example changes the id="demo"

The content of the element:

<html>
<body>

<p id="demo"></p>

<script>
	document.getElementById("demo").innerHTML = "Hello World!";
</script>

</body>
</html>

In the above example, getElementById is the method and innerHTML is the property.

getElementById method

The most common way to access an HTML element is by using the element's id.

In the above example, the getElementById method uses id="demo" to find the element.

innerHTML attribute

The easiest way to get the content of an element is to use the innerHTML property.

The innerHTML property can be used to get or replace the content of an HTML element.

The innerHTML property can be used to get or change any HTML element, including and .

3.3. Finding elements

method describe
document.getElementById(id) Find elements by element id
document.getElementsByTagName(name) Find elements by tag name
document.getElementsByClassName(name) Find elements by class name
document.querySelector() Returns the first element in the document that matches the specified CSS selector
document.querySelectorAll() document.querySelectorAll() is a new method introduced in HTML5 that returns a list of all element nodes that match the CSS selector in the document
getElementById()

Returns an element matching the specified id.

<div id="d1">我是一个div标签</div>
<script>
  // 查找id为d1的标签
  var div = document.getElementById('d1');
  console.log(div);
</script>
getElementsByTagName()

Returns a HTMLCollection(pseudo-array) containing all elements matching the specified tag name.

<p>我是p标签</p>
<p>我是p标签</p>
<p>我是p标签</p>
<script>
  // 查找所有p标签
  var p = document.getElementsByTagName('p');
  console.log(p);
</script>
getElementsByClassName()

Returns an HTML collection HTMLCollection(pseudo-array) containing all elements matching the specified class name.

<div class="div1">我是div标签</div>
<div class="div1">我是div标签</div>
<div class="div1">我是div标签</div>
<script>
  // 查找class为div1的标签
  var div = document.getElementsByClassName('div1');
  console.log(div);
</script>
document.querySelector()

Returns the first element in the document that matches the specified CSS selector

<div id="div1">我是一个div</div>
<div id="div1">我是一个div</div>
<script>
  document.querySelector("#div1").innerHTML = "Hello World!";
</script>
document.querySelectorAll()

document.querySelectorAll() is a new method introduced in HTML5 that returns a list of all element nodes that match the CSS selector in the document

<div class="div1">我是一个div</div>
<div class="div1">我是一个div</div>
<script>
  console.log(document.querySelectorAll(".div1"));
  var x = document.querySelectorAll(".div1");
  x[0].innerHTML = '我是新的div';
</script>

3.4. Adding elements

document.createElement(element)

Creates a new HTML element to be used in conjunction with the appendChild() or insertBefore() methods. Among them, the appendChild() method adds a new child node at the end of the node's child node list. The insertBefore() method inserts a new node anywhere in the node's child node list.

<script>
  // 创建元素节点p
  var p = document.createElement('p');
  // 向p标签插入内容
  p.innerHTML = '我是一个p标签';
  // 将节点插入到body中
  document.body.appendChild(p);
</script>

3.5. Write

document.write()

Write text or HTML expressions or JavaScript code to the document.

<script>
  document.write("<p>Hello world!</p>");
  document.write("<span>Hello DOM!</span>");
  document.write("Hello Weekend!");
</script>

4.Element type

Element objects correspond to HTML elements of web pages. Every HTML element will be transformed into an Element node object on the DOM tree.

4.1. Properties

attributes: Returns a collection of all attributes associated with this element.

classList: Returns the collection of class attributes contained in the element.

className: Gets or sets the value of the class attribute of the specified element.

clientHeight: Gets the height inside the element, including padding, but excluding horizontal scrollbars, borders, and margins.

clientTop: Returns the height of the element from its upper border.

clientLeft: Returns the width of the element from its left border.

clientWidth: Returns the width of the element inside it, including padding, but excluding vertical scroll bars, borders, and margins.

innerHTML: Set or get the descendant of the element represented by HTML syntax.

tagName: Returns the tag name of the current element.

4.2. Common methods

method describe
element.innerHTML = new html content Change the innerHTML of an element
element.attribute = value Modify the value of an attribute
element.getAttribute() Returns the value of the specified attribute of the element node.
element.setAttribute(attribute, value) Set or change attribute values ​​of HTML elements
element.style.property = new style Change the style of HTML elements
element.innerHTML

Property sets or gets the descendant of the element represented by HTML syntax.

<div id="div1">我是一个div</div>
<script>
  var d1 = document.getElementById('div1');
  // 获取
  console.log(d1.innerHTML);
  // 设置
  d1.innerHTML = '我是新的内容'
</script>
element.attribute = value

Modify the value of an existing attribute

<div id="div1">123</div>
<script>
  var d1 = document.getElementById('div1');
  // 直接将已经存在的属性进行修改
  d1.id = 'div2';
</script>
element.getAttribute()

Returns the value of the specified attribute of the element node.

<div id="div1">我是一个div</div>
<script>
  var div = document.getElementById('div1');
  console.log(div.getAttribute('id')); // div1
</script>
element.setAttribute(attribute, value)

Sets or changes the specified property to the specified value.

<div id="div1">我是一个div</div>
<script>
  var d1 = document.getElementById('div1');
  // 设置div1的class为divCla
  d1.setAttribute('class', 'divCla');
</script>
element.style.property

Sets or returns the element's style attribute.

<div id="div1">我是一个div</div>
<script>
  var d1 = document.getElementById('div1');
  // 获取div1的style样式
  console.log(d1.style);
  // 设置div1的style
  d1.style.backgroundColor = 'red';
</script>

For other details, please refer to https://www.w3school.com.cn/jsref/dom_obj_all.asp

https://developer.mozilla.org/zh-CN/docs/Web/API/Element

5. Text type

Text nodes, represented by the Text type, contain literal plain text and may contain escaped HTML characters, but no HTML code.

5.1. Properties and methods

length

​ text length

appendData(text)

​ Append text

deleteData(beginIndex,count)

​ delete text

insertData(beginIndex,text)

​ Insert text

replaceData(beginIndex,count,text)

​ replace text

splitText(beginIndex)

​ Divide the current text node into two text nodes from the position of beginIndex

document.createTextNode(text)

​ Create a text node, the parameter is the text to be inserted into the node

substringData(beginIndex,count)

​ Extract count substrings from beginIndex

Comprehensive case
<div id="container"></div>
<script>
  // 创建文本节点
  var textNode = document.createTextNode('Hello World!');
  // 获取container
  var div = document.getElementById('container');
  // 将文本节点插入container
  div.appendChild(textNode);
  // 替换文本
  textNode.replaceData(0,5,'Hi');
  // 插入文本
  textNode.insertData(0, 'Hello')
</script>

Guess you like

Origin blog.csdn.net/qq_63299825/article/details/131565232