catalogue
Node parent, child, and sibling
(4) Child nodes first and last
1. Common ways to find HTML elements
(2) querySelector and querySelectorAll
(3) Get special elements (body, html)
(2) Attribute operation of common elements
5. Create, add, delete, copy nodes
(4) Replication node (clone node)
(5) Differences between three dynamic creation elements
1, Introduction to DOM
DOM (Document Object Model) is translated into document object model, which is the programming interface of HTML and XML documents.
The HTML DOM defines standard methods for accessing and manipulating HTML documents.
DOM expresses HTML documents in a tree structure.
Through the programmable object model, JavaScript has gained enough ability to create dynamic HTML:
- JavaScript can change all HTML in a page
- JavaScript element can change all HTML attributes in a page
- JavaScript can change all CSS styles in a page
- JavaScript can respond to all events in the page
2, HTML DOM tree structure:
- Document: a page is a document, which is represented by document in DOM
- Element: all tags in the page are elements, which are represented by element in DOM
- Node: all contents in a web page are nodes (labels, attributes, text, comments, etc.), which are represented by node in DOM
3, DOM node
According to the W3C HTML DOM standard, all contents in HTML documents are nodes:
- The entire document is a document node
- Each HTML element is an element node
- The text within an HTML element is a text node
- Each HTML attribute is an attribute node
- Annotations are annotation nodes
Node type
- Element node nodeType is 1
- The attribute node nodeType is 2
- The text node nodeType is 3 (the text node contains text, spaces, line breaks, etc.)
Node parent, child, and sibling
Nodes in the node tree have hierarchical relationships with each other.
We often use terms such as parent, child and sibling to describe these relationships. The parent node has child nodes. Children of the same level are called siblings (brothers or sisters).
- In the node tree, the top node is called root.
- Every node has a parent, except the root (it has no parent).
- A node can have any number of child nodes.
- Siblings are nodes that have the same parent node.
The following picture shows a part of the node tree and the relationship between nodes:
(1) Parent node
node.parentNode
- The parentNode property returns the parent node of a node. Note that it is the nearest parent node
- Returns null if the specified node has no parent node
(2) Child nodes
parentNode.childNodes(Standard)
<ul> <li>I am li</li> <li>I am li</li> <li>I am li</li> <li>I am li</li> </ul> var ul = document.querySelector('ul'); var lis = ul.querySelectorAll('li'); // 1. Child nodes all child nodes include element nodes, text nodes, etc console.log(ul.childNodes);
result:
The newline belongs to the text node
for(var i = 0; i < ul.childNodes.length;i++) { if (ul.childNodes[i].nodeType == 1) { // ul.childNodes[i] is an element node console.log(ul.childNodes[i]); } }
(3) Child nodes
parentNode.children(Non standard)
(4) Child nodes first and last
parentNode.firstChild
firstChild returns the first child node. If it cannot be found, it returns null. Similarly, it contains all nodes.
parentNode.lastChild
parentNode.firstElementChild
firstElementChild returns the first child element node. If it cannot be found, it returns null.
parentNode.lastElementChild
lastElementChild returns the last child element node. If it cannot be found, it returns null.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <ol> <li>I am li1</li> <li>I am li2</li> <li>I am li3</li> <li>I am li4</li> <li>I am li5</li> </ol> <script> var ol = document.querySelector('ol'); // 1. The first child node of firstchild is either a text node or an element node console.log(ol.firstChild); console.log(ol.lastChild); // 2. firstElementChild returns the first child element node ie9 to support console.log(ol.firstElementChild); console.log(ol.lastElementChild); // 3. The actual development method has no compatibility problem and returns the first child element console.log(ol.children[0]); console.log(ol.children[ol.children.length - 1]); </script> </body> </html>
result:
(5) Sibling node
The same as above, directly on the code
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <div>I am div</div> <span>I am span</span> <script> var div = document.querySelector('div'); // 1. The next sibling node of nextsibling includes element node or text node, etc console.log(div.nextSibling); console.log(div.previousSibling); // 2. Nextlementsibling gets the next sibling element node console.log(div.nextElementSibling); console.log(div.previousElementSibling); </script> </body> </html>
4, DOM object
When the browser loads an HTML Document, it becomes a Document object
The Document object is the root node of the HTML Document
The Document object enables us to access all the elements in the HTML page from the script
Tip: Document object is a part of Window object, which can be accessed through Window The Document property accesses it.
1. Common ways to find HTML elements
(1) get method
method | describe |
---|---|
getElementById() | Returns the element with the specified ID. |
getElementsByTagName() | Returns a node list (collection / node array) containing all elements with the specified label name. |
getElementsByClassName() | Returns a list of nodes containing all elements with the specified class name. |
// Return node with ID 'test': var test = document.getElementById('test'); // Locate the node with ID 'test table' first, and then return all tr nodes inside it: var trs = document.getElementById('test-table').getElementsByTagName('tr'); // Locate the node with ID 'test div' first, and then return all nodes whose internal class contains red: var reds = document.getElementById('test-div').getElementsByClassName('red');
(2) querySelector and querySelectorAll
Note: the selectors in querySelector and querySelectorAll need to be signed, for example:
document.querySelector('#nav');
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <div class="box">Box 1</div> <div class="box">Box 2</div> <div id="nav"> <ul> <li>home page</li> <li>product</li> </ul> </div> <script> // 1. getElementsByClassName obtains some element collections according to the class name var boxs = document.getElementsByClassName('box'); console.log(boxs); // 2. querySelector returns the first element object of the specified selector. Remember that the selector in it needs to be signed box #nav var firstBox = document.querySelector('.box'); console.log(firstBox); var nav = document.querySelector('#nav'); console.log(nav); var li = document.querySelector('li'); console.log(li); // 3. querySelectorAll() returns the collection of all element objects of the specified selector var allBox = document.querySelectorAll('.box'); console.log(allBox); var lis = document.querySelectorAll('li'); console.log(lis); </script> </body> </html>
(3) Get special elements (body, html)
2. Event basis
Before learning the addition, deletion, modification and query of DOM, let's first understand what events are.
(1) Event overview
(2) Three elements of event
- Event source (who)
- Event type (what event)
- Event handler (what to do)
example
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <button id="btn">Tang Bohu</button> <script> // Click a button to pop up a dialog box // 1. An event is an event handler that consists of three parts: an event source, an event type, and an event handler //(1) Event source the object whose button the event is triggered var btn = document.getElementById('btn'); //(2) How do event types trigger events, such as onclick, mouse over or keyboard down //(3) The event handler is completed by a function assignment btn.onclick = function() { alert('Point Qiuxiang'); } </script> </body> </html>
(3) Event summary
Some common events are summarized below.
Mouse event
attribute | describe |
---|---|
onclick | The event handle called when the user clicks on an object. |
oncontextmenu | Triggered when the user clicks the right mouse button to open the context menu |
ondblclick | The event handle called when the user double clicks an object. |
onmousedown | The mouse button is pressed. |
onmouseenter | Triggered when the mouse pointer moves over an element. |
onmouseleave | Triggered when the mouse pointer moves out of the element |
onmousemove | The mouse is moved. |
onmouseover | Move the mouse over an element. |
onmouseout | Move the mouse away from an element. |
onmouseup | The mouse button is released. |
Keyboard events
attribute | describe |
---|---|
onkeydown | A keyboard key is pressed. |
onkeypress | A keyboard key is pressed and released. |
onkeyup | A keyboard key is released. |
Form Events
attribute | describe |
---|---|
onblur | Triggered when the element loses focus |
onchange | This event is triggered when the content of the form element changes (< input >, < keygen >, < Select >, and < textarea >) |
onfocus | Triggered when the element gets focus |
onfocusin | Triggered when the element is about to get focus |
onfocusout | Triggered when the element is about to lose focus |
oninput | Triggered when the element gets user input |
onreset | Triggered when the form is reset |
onsearch | Triggered when the user enters text into the search field (< input = "search" >) |
onselect | Triggered when the user selects text (< input > and < textarea >) |
onsubmit | Triggered when the form is submitted |
Clipboard events
attribute | describe |
---|---|
oncopy | This event is triggered when the user copies the element content |
oncut | This event is triggered when the user cuts the element content |
onpaste | This event is triggered when the user pastes the element content |
See the following link for the full version of the event: https://www.runoob.com/jsref/dom-obj-event.html
3. Change element content
(1) innerText and innerHTML
element.innerText
The content from the start position to the end position, but it removes html tags, as well as spaces and line breaks
element.innerHTML
All contents from the start position to the end position, including html tags, while retaining spaces and line breaks
(2) Attribute operation of common elements
1. innerText,innerHTML Change element content 2. src,href 3. id,alt,title
(3) Style attribute action
1. element.style Inline style operation 2. element.className Class name style operation
Note 1:
(4) Case
See:
Exclusive thought in javascript
javascript: click the small picture to switch the background picture
javascript:dom case list enables all check boxes to be deselected
4. Custom properties
(1) Get property value
- element. Attributes
- element.getAttribute('attribute ')
- element. Property to get the built-in attribute value (the attribute of the element itself)
- element.getAttribute('attribute '); Mainly get custom attributes (standard) our programmers' custom attributes
(2) Set attribute value
- element. Attribute = 'value'
- element.setAttribute('attribute ',' value ')
- element. Property sets the built-in property value
- element.setAttribute('attribute '); Mainly set custom properties (standard)
(3) Remove attribute
- element.removeAttribute('attribute ')
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <div id="demo" index="1" class="nav"></div> <script> var div = document.querySelector('div'); // 1. Get the attribute value of the element // (1) element. attribute console.log(div.id); //(2) element.getAttribute('attribute ') get the meaning of getting attribute attribute. The attribute added by our programmers is called user-defined attribute index console.log(div.getAttribute('id')); console.log(div.getAttribute('index')); // 2. Set element attribute value // (1) element. Attribute = 'value' div.id = 'test'; div.className = 'navs'; // (2) element.setAttribute('attribute ',' value '); Mainly for custom attributes div.setAttribute('index', 2); div.setAttribute('class', 'footer'); // Class is special. It says class, not className // 3 remove the attribute removeattribute (attribute) div.removeAttribute('index'); </script> </body> </html>
(4) H5 custom attributes
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <div getTime="20" data-index="2" data-list-name="andy"></div> <script> var div = document.querySelector('div'); console.log(div.getTime); console.log(div.getAttribute('getTime')); div.setAttribute('data-time', 20); console.log(div.getAttribute('data-index')); console.log(div.getAttribute('data-list-name')); // h5 is a new method to get custom attributes. It can only get the attributes beginning with data - // dataset is a collection containing all custom attributes starting with data console.log(div.dataset); console.log(div.dataset.index); console.log(div.dataset['index']); // If there are multiple - linked words in the custom attribute, we use the hump naming method when obtaining them console.log(div.dataset.listName); console.log(div.dataset['listName']); </script> </body> </html>
5. Create, add, delete, copy nodes
(1) Create node
(2) Add node
(3) Delete node
(4) Replication node (clone node)
(5) Differences between three dynamic creation elements
- document.write()
- element.innerHTML
- document.createElement()
- document.write is the content stream that directly writes the content to the page, but when the document stream is completed, it will cause all pages to be redrawn
- innerHTML is to write the content to a DOM node, which will not cause all pages to be redrawn
- innerHTML is more efficient in creating multiple elements (don't splice strings, splice them in the form of arrays), and the structure is slightly complex
- createElement() is a little less efficient in creating multiple elements, but its structure is clearer