DOM node operation, event, BOM

1. Node operation

1.1 what is a node

According to the W3C HTML DOM standard, all contents in HTML documents are nodes;

The whole document is a document node document

The text within each HTML element is a text node

Text nodes within HTML elements

Each HTML attribute is an attribute node

Annotations are annotation nodes

1.2 node type

The noteType property allows you to obtain the type of node

Node type of document ----- 9

console.log(document.noteType);//9

Node type of label - 1

var box1 = document.getElementById('box1');

console.log(box1.nodeType);//1

Node type of attribute ----- 2, getattrbutenode ("attribute"): get the attribute node of the element

var attr1 = box1.getAttrbuteNode("class"); 

console.log(attr1.nodeType);//2

Text node type ----- 3. The first child node of the element is the text node

console.log(box1.firstChild.nodeType)//3 

1.3 node name  

nodeName allows you to get the node name of the element

Node name of document -----#document

console.log(document.nodeName);//#document

Node name of label ----- upper case label name

console.log(box1.nodeName);//#DIV 

Node name of attribute ----- attribute name

console.log(attr1.nodeName);//class 

Node name of text -----#text

console.log(box1.fristChild.nodeName);//#text 

1.4 node value  

nodeValue allows you to get the value of the node of the element

Node value of document ----- null

console.log(document.nodeValue);//null

Node value of tag ----- null

console.log(document.nodeValue);//null 

Node value of attribute ----- attribute value

console.log(attr.nodeValue);//boxCl 

Node value of text ----- content of text

console.log(box.firstChild.nodeValue);// I'm a div element  

2. Relationship between nodes

2.1 HTML DOM node tree

HTML DOM   Treat HTML documents as a tree structure, which is called a node tree

  Through HTML DOM, all nodes in the tree can be accessed through JavaScript. All HTML elements (nodes) can be modified, and nodes can be created or deleted.

2.2 relationship between nodes

The relationship between nodes is nested (parent-child relationship) and juxtaposed (sibling relationship). Note the difference between nodes and element nodes.
Parent node -- parentNode
Parent element node -- parentElement
Child nodes: label nodes, text nodes, and comment nodes   The result is a pseudo array
Child element node -- children: label node
First child node -- firstChild: Text
First child element node -- firstElementChild: first label
  Last child node -- lastChild: Text
Last child element node -- lastElementChild: last label
Previous child node -- previousSibling: Text
Previous child element node -- previousElementSibling: previous label
Next child node -- nextSibling: Text
Next child element node -- nextlementsibling: next label
Summary: firstChild, lastChild, previousSibling and nextSibling get text. If not, it is the text node name #text. firstElementChild, lastElementChild, previousElementSibling and nexterelementsibling get labels. If not, it is empty.


2.3 node interlaced color change

The interlaced color change we learned before is through traversing the pseudo array and then judging odd and even numbers, or cyclic accumulation time + 2. Now I use the relationship between nodes and the name and value of nodes to achieve the effect of interlaced color change

The first: odd even judgment

for (var i = 0; i < liObj.length; i++) {
     if (i % 2 == 0) {
       liObj[i].style.backgroundColor = "red";
     }
   }

The second: accumulation 2

for (var i = 0; i < liObj.length; i += 2) {
    liObj[i].style.backgroundColor = "red";
  } 

Third: child element node

for (var i = 0; i < ulObj.children.length; i++) {
    if (i % 2 == 0) {
      liObj[i].style.backgroundColor = "red";
    }
  }

The fourth is node operation

 for (var i = 0; i < ulObj.childNodes.length; i++) {
    // console.log(ulObj.childNodes[i]);
    // Judge whether it is a label node and extract the label node
    if (ulObj.childNodes[i].nodeType == 1 && ulObj.childNodes[i].nodeName == "LI") {
      console.log(ulObj.childNodes[i]);
      newObj.push(ulObj.childNodes[i]);
    }
  }
  for (var i = 0; i < newObj.length; i++) {
    if (i % 2 == 0) {
      newObj[i].style.backgroundColor = "red";
    }
  }

2.4 inserting nodes

The insertBefore() method inserts a new child node before the existing child node.

Tips:   If you want to create a new text list item, you should add the text node of the element after the LI element, and then add the LI element to the list.

You can also use the insertBefore method to insert / remove existing elements.

node.insertBefore(newnode,existingnode) parameter newnode is the node object to be inserted, and existingnode is the child node before the new node is added.

var node=document.getElementById("myList2").lastChild;
var list=document.getElementById("myList1");
list.insertBefore(node,list.childNodes[0]);

3. Three ways to create elements

3.1 document.write()

Disadvantages: you can only add elements to the body

document.write('<div   Class = "box1" > I'm div < / div >);

3.2 innerHTML 

Disadvantages: only one element can be added under the same level, and multiple elements will be overwritten

   document.getElementById("divObj").innerHTML  =  "< p > hahaha < / P >";

3.3 document.createElement() 

Parent element. AppendChild (child element): adds child elements to the end of the parent element

var pObj = document.createElement("p");

  divObj1.appendChild(pObj);

3.4 dynamic creation list  

Click the button to dynamically create an unordered list and render it in the box with red border

Idea: 1. Create a content array

  1. Get the element and bind the click event to the button
  2. Create ul tag
  3. Add ul to box
  4. Traversal array
  5. Create li label
  6. Add content
  7. Button disabled
  8. <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <style>
            #btn {
                width: 300px;
                height: 100px;
            }
    
            #box {
                width: 300px;
                border: 2px solid;
                margin-top: 30px;
            }
    
            ul {
                list-style: none;
            }
    
            .red {
                color: red;
            }
        </style>
    </head>
    
    <body>
        <button id="btn">get data</button>
        <div id="box"></div>
    </body>
    <script>
        // Data obtained in the background
        var dataArr = ['How important is the Sixth Plenary Session of the 19th CPC Central Committee', '31 7 newly diagnosed cases in provinces, autonomous regions and cities', '3.6 How did the resolution of more than 10000 words come into being', 'Sydney and Lin Shanshan were fined more than 90 million for tax evasion', 'Chinese and American players will form teams to compete in the mixed doubles of the world table tennis championships', 'Taiwan Far East Group's investment enterprises in the mainland were investigated and dealt with'];
        /**
         * Render the data in the form of a list into #box
         * And each data binding moves in and out events, moves in color change, and moves out recovery
         */
        var boxObj1 = document.getElementById('box');
        //Create div object
        var button = document.getElementById('btn');
        //Create a dom object
        button.onclick = function () {
            //Bind click event
            var uObj = document.createElement('ul');
            //Create element ul
            boxObj1.appendChild(uObj);
            //Insert ul into div
            for (let i = 0; i < dataArr.length; i++) {
                //Traverse the array to get each item in the array
                var lObj = document.createElement('li');
                //Create li element
                uObj.appendChild(lObj);
                //Insert li in ul
                lObj.innerHTML = dataArr[i];
                //Output on page
                lObj.onmouseover = function () {
                    this.className = 'red';
                }
                lObj.onmouseout = function () {
                    this.className = '';
                }
    
            }
        }
    </script>
    
    </html>

    4. Advanced events

4.1 three elements of event

Event source: refers to the event triggered by that element. For example, when you click the cdsn icon, you will jump to the cdsn home page. Then the cdsn icon is the event source. Or, it can be understood that when you perform an action on an element, a series of effects (animation, jump...) will be triggered. Then this element is the event source.

Event type: for example, click, mouse over, press the keyboard to get focus.

Event driver: the event driver is the result of execution. For example, when you click the cdsn icon, you will jump to the cdsn home page. Then jump to the cdsn home page is the event processing result.

Steps to execute events: get elements, bind events, and write event drivers

4.2 listening events

Binding listening events   addEventListener("type of event", handler of event)

box1.addEventListener("click", myFunc)
  function myFunc() {
    this.style.backgroundColor = "blue";
  }

  Unbind the listening event removeEventListener("event type", event handler)

 

 box1.removeEventListener("click", myFunc);

4.3 event object

Any event has a built-in object event. The compatibility of the event object is written as

var event = event || window.event;
// Type of event
    console.log(event.type);
    // ID of the element
    console.log(event.target.id);
    // Content of text
    console.log(event.target.innerText);
    // The trigger point of the event is the abscissa and ordinate to the left of the browser
    console.log("Abscissa:" + event.clientX + "," + "Ordinate:" + event.clientY);
    console.log("Abscissa:" + event.pageX + "," + "Ordinate:" + event.pageY);
    console.log("I click header!");

4.4 event bubbling

What is a bubbling event

Event bubbling stage: the event starts from the event target and bubbles up to the top label of the page.
Suppose an element div has a subordinate element p.
<div>
< p > element</p>
</div>
Both elements are bound click event , if the user clicks p, it triggers on both div and p click event , which of the two event handlers executes first? What is the sequence of events?

How to prevent bubbling (compatibility exists)

e.stopPropagation(); Google and Firefox support,

window.event.cancelBubble=true; IE specific, supported by Google, not supported by Firefox

 5. BOM

5.1 concept of BOM

BOM(Browser Object Model) refers to the browser object model, which provides an object structure independent of content and can interact with the browser Window. The BOM consists of multiple objects. The Window object representing the browser Window is the top-level object of the BOM, and other objects are sub objects of the object.

Some of our operations in the browser can be programmed using BOM,

For example: refresh the browser, back, forward, enter the URL in the browser, etc

5.2 top level object of BOM

Window is the top-level object of the browser. When calling the properties and methods under window, you can omit window. Note: a special property under window, window.name

5.3 dialog box

alert()

prompt()

confirm()

5.4 loading events

onload event

The onload event occurs immediately after the page or image is loaded.

onload is usually used for < body > elements to execute script code after the page is fully loaded (including images, css files, etc.).

5.5 Location object

Common properties

// //Contents on # and after the address bar
// console.log(window.location.hash);
// //Host name and port number
// console.log(window.location.host);
// //Host name
// console.log(window.location.hostname);
// //File path --- relative path
// console.log(window.location.pathname);
// //Port number
// console.log(window.location.port);
// //Agreement
// console.log(window.location.protocol);
// //What to search for
// console.log(window.location.search);

5.6 History object

//Jump
my$("btn1").onclick = function () {
window.location.href = "15test.html";
};
//forward
my$("btn2").onclick = function () {
window.history.forward();
};
//back off
my$("btn").onclick = function () {
window.history.back();
};

5.7 Navigator object

adopt userAgent You can determine the type of user browser
console.log(window.navigator.userAgent);
//The platform can be used to determine the system platform type of the browser
//console.log(window.navigator.platform);

6. Timer

6.1 setInteval()

The setInterval() method calls a function or evaluates an expression for a specified period (in milliseconds).

The setInterval() method keeps calling the function until   clearInterval()   Called or window closed. The ID value returned by setInterval() can be used as an argument to the clearInterval() method.

clearInteval()

The clearInterval() method cancels the scheduled execution set by the setInterval() function.

The parameter to the clearInterval() method must be the ID value returned by setInterval().

//Timer

//Parameter 1: function

//Parameter 2: time -- milliseconds -- 1000 milliseconds -- 1 second

//Execution process: after the page is loaded, execute the function code once after 1 second, and then execute the function after 1 second

//The return value is the id value of the timer

6.2 setTimeot()

Another timer definition and usage

Method is used to call functions or compute expressions after specified milliseconds.

Tips:   1000 ms = 1 second.

Tips:   If you just want to repeat, you can use   setInterval()   method.

Tips:   use   clearTimeout()   Method to prevent the execution of the function.

Parameter: param1 callback function, param2 time

Return value:   Returns an ID (number) that can be passed to clearTimeout() to cancel execution

Tags: Front-end css3 html css

Posted on Mon, 22 Nov 2021 21:00:38 -0500 by midge1970