JavaScript: Dom knowledge points summary

catalogue

1, Introduction to DOM

2, HTML DOM tree structure:

3, DOM node

Node type

Node parent, child, and sibling

(1) Parent node

(2) Child nodes

(3) Child nodes

(4) Child nodes first and last

(5) Sibling node

4, DOM object

1. Common ways to find HTML elements

(1) get method

(2) querySelector and querySelectorAll

(3) Get special elements (body, html)

2. Event basis

(1) Event overview

(2) Three elements of event

(3) event summary

3. Change element content

(1) innerText and innerHTML

(2) Attribute operation of common elements

(3) Style attribute action

(4) Case

4. Custom properties

(1) Get property value

(2) Set attribute value

(3) Remove attribute

(4) H5 custom attributes

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

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

Generally, a node has at least three nodes: nodeType, nodeName, and nodeValue
Basic properties.
  • 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.)
In our actual development, the main operations of node operation are Element node

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)
parentNode.childNodes Returns the name of the child node that contains the specified node aggregate , which is a collection of immediate updates.
be careful: The return value contains all child nodes, including element nodes, text nodes, etc.
For example:
<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

If you only want to get the element nodes inside, you need to deal with them specially. Therefore, we generally do not advocate the use of childNodes
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)
parentNode.children Is a read-only property and returns All child element nodes . It only returns child element nodes, and other nodes do not return( This is what we focus on ).
Although children is a non-standard, it is supported by various browsers, so we can use it safely

(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
lastChild returns the last child node. If it cannot be found, it returns null. Similarly, it contains all nodes.
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

methoddescribe
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)

Get body element
doucumnet.body // return body Element object
Get html element
document.documentElement // return html Element object

2. Event basis

Before learning the addition, deletion, modification and query of DOM, let's first understand what events are.

(1) Event overview

JavaScript enables us to create dynamic pages, and events are behaviors that can be detected by JavaScript.
Simple understanding: Trigger response mechanism .
Each element in the web page can generate some events that can trigger JavaScript. For example, we can generate an event when the user clicks a button, and then perform some operations

(2) Three elements of event

  1. Event source (who)
  2. Event type (what event)
  3. 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

attributedescribe
onclickThe event handle called when the user clicks on an object.
oncontextmenuTriggered when the user clicks the right mouse button to open the context menu
ondblclickThe event handle called when the user double clicks an object.
onmousedownThe mouse button is pressed.
onmouseenterTriggered when the mouse pointer moves over an element.
onmouseleaveTriggered when the mouse pointer moves out of the element
onmousemoveThe mouse is moved.
onmouseoverMove the mouse over an element.
onmouseoutMove the mouse away from an element.
onmouseupThe mouse button is released.

Keyboard events

attributedescribe
onkeydownA keyboard key is pressed.
onkeypressA keyboard key is pressed and released.
onkeyupA keyboard key is released.

Form Events

attributedescribe
onblurTriggered when the element loses focus
onchangeThis event is triggered when the content of the form element changes (< input >, < keygen >, < Select >, and < textarea >)
onfocusTriggered when the element gets focus
onfocusinTriggered when the element is about to get focus
onfocusoutTriggered when the element is about to lose focus
oninputTriggered when the element gets user input
onresetTriggered when the form is reset
onsearchTriggered when the user enters text into the search field (< input = "search" >)
onselectTriggered when the user selects text (< input > and < textarea >)
onsubmitTriggered when the form is submitted

Clipboard events

attributedescribe
oncopyThis event is triggered when the user copies the element content
oncutThis event is triggered when the user cuts the element content
onpasteThis 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

We can modify the size, color, position and other styles of elements through JS.
1. element.style Inline style operation
2. element.className Class name style operation

Note 1:

1.JS The style inside adopts the hump naming method, such as fontSize , backgroundColor
2.JS modify style The style operation generates an inline style, CSS High weight
Note 2 :
1. If the style is modified more, you can change the element style by operating the class name.
2. class Because it is a reserved word, it is used className To manipulate the element class name attribute
3. className The class name of the element will be changed directly and the original class name will be overwritten

(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 ')

difference:
  • 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 ')

difference:
  • 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

Custom attribute purpose: to save and use data. Some data can be saved to the page instead of the database.
The custom attribute is obtained through getattribute(‘ attribute ') obtain.
However, some custom attributes are easy to cause ambiguity, and it is not easy to judge whether they are built-in attributes or custom attributes of elements.
H5 Added custom attributes to us:
1. Set H5 custom attribute
H5 specifies that the beginning of the custom attribute data - is used as the attribute name and assigned a value.
For example, < div data index = "1" > < / div >
Or use JS settings
element.setAttribute('data-index', 2)
2. Get H5 custom attribute
1.
Get compatibility element getAttribute(‘data-index’);
2.
H5 new element dataset . index or element.dataset ['index'] ie 11 began to support
<!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

document.createElement('tagName')
document.createElement() Method created by tagName designated HTML Element. Because these elements didn't exist,
It is dynamically generated according to our requirements, so it is also called Dynamically create element nodes.

(2) Add node

1. node.appendChild(child)
node.appendChild() Method to add a node to the child node list of the specified parent node end . be similar to CSS Inside
after Pseudo element.
2. node.insertBefore(child, specify element)
node.insertBefore() Method to add a node to the specified child node of the parent node front . be similar to CSS Inside before
Pseudo element.

(3) Delete node

node.removeChild(child)
node.removeChild() Method from DOM Delete a child node in the and return the deleted node.

(4) Replication node (clone node)

node.cloneNode()
node.cloneNode() Method returns a copy of the node that called the method. Also known as clone node / copy node
be careful:
1. If the parameter in parentheses is Empty or empty false , yes Shallow copy That is, only the replication node itself is cloned, and the child nodes inside are not cloned.
2. If the parameter in parentheses is true , yes Deep copy , the node itself and all its child nodes will be copied.

(5) Differences between three dynamic creation elements

  • document.write()
  • element.innerHTML
  • document.createElement()
difference
  1.  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
  2. innerHTML is to write the content to a DOM node, which will not cause all pages to be redrawn
  3. 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
  4. createElement() is a little less efficient in creating multiple elements, but its structure is clearer
summary : In different browsers, innerHTML More efficient than creatElement high

Keywords: Javascript Front-end DOM

Added by .Stealth on Mon, 17 Jan 2022 10:36:17 +0200