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


Node type of label -- 1

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

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

var attr1=box!.getAttributeNode("class");

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


1.3 node name

You can get the node name of the element through nodeName

Node name of document --#document


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


Node name of attribute --- attribute name


Node name of text ---#text


1.4 node value

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

Node value of document -- null


Node value of label -- null


Node value of attribute --- attribute value


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") {
  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");

3. Three ways to create elements


Disadvantages: you can only add elements to the body

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


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>";


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

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

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() { = "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
    //  ID of the element
    //  Content of text
    //  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.
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.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,

5.3 dialog box




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(;
// //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(;

5.6 history object

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

5.7 Navigator object

adopt userAgent You can determine the type of user browser
//The platform can be used to determine the system platform type of the browser

6. Timer


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.


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


//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


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