Front end day 8 DOM node operation / event alignment and 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 entire document is a document node   document

Each HTML   An 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

1.2 node type

The noteType property allows you to obtain the type of node

Node type of document -- 9

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

Node type of label -- 1

var box1=document.getElementById("box1");
console.log(box.nodeType);//1

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

var attr1=box!.getAttributeNode("class");
console.log(attr1.nodeType);//2

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

console.log(box.firstChild.nodeType);//3

1.3 node name

You can get the node name of the element through nodeName

Node name of document --#document

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

Node name of the label ---# upper case label name

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

Node name of attribute --- attribute name

consold.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 label -- null

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

Node value of attribute --- attribute value

console.log(attr1.nodeValue);//boxC1

Node value of text --- content of text

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

2. Relationship between nodes

2.1 HTML DOM node tree

The HTML DOM regards the HTML document 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, or nodes can be created or deleted

2.2 relationship between nodes

The relationship between nodes is nested relationship (parent-child relationship) / juxtaposition relationship (sibling relationship). Pay attention to the difference between nodes and element nodes

Parent node--   parentNode

Parent element node -- parentElement

Child node = childNodes: label node / text node / comment node   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 -- nexterementsibling   Next label

Summary: fristChild/lastChild/previousSibling/nextSibling get all text, if not, it is the text node name #text. Firstelementchild / lastelementchild / previouselementsibling / nexterelementsibling get all labels, if not, it is empty

2.3 node interlaced color change

The interlaced color change we have learned is to traverse the pseudo array and then judge the odd and even number. If the cyclic accumulation is + 2, now we 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 1=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 node

Japanese: if you want to create a new text column option, you should add the text node of the element after the LI element

Then add the LI element to the list

You can also use the inserBefore method to insert / overflow and existing elements

node.inserBefore(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.1document.write()

Disadvantages: you can only add elements to the body

document.write('<div class="box1">I am div</div>');

3.2innerHTML

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

document.getElementById("divObj").innerHTML = "<p>Ha ha ha</p>";

3.3document.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

  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.1BOM concept

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.1setlntaval()

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.2setTimeout()

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 html css

Posted on Mon, 22 Nov 2021 10:48:45 -0500 by sandstorm140