Introduction of the DOM

DOM is a bridge between HTML and CSS

◆ DOM (Document Object Model, Document Object Model) is the interface of JavaScript to operate HTML documents,DOM gives us to add, remove and modify page elements (make the Document operation become very elegant, simple. (The text of the element is also a node of the DOM.)

◆ The biggest feature of DOM is that documents are represented as nodes.

Accessing element nodes

◆ the so-called “access” element node, refers to “get”, “get” page element node

◆ The operation of the node, the first step is to get it

Access element nodes mainly rely on the Document object

Understanding the Document object

◆ Document object is the most important thing in DOM, almost all DOM functions are encapsulated in the Document object

The document object also represents the entire HTML document, which is the root of the DOM node tree

How to get elements

Can be used directly in JS without getting the id name

document.getElmentById()

Get the element by ID

◆ If there are elements with the same ID on the page, only the first one can be obtained

◆ No matter how deep the hidden element is, it can be found by id

document.getElmentById(a)Copy the code

getElementsByClassName()

Gets an array of elements by class name

Incompatible with IE8 and below

document.getElementsByClassName(a)Copy the code

getElementsByTagName()

Gets an array of elements by tag name

Array easy traversal, so you can batch control element nodes

Even if there is only one node on the page with the specified label name, you will get an array of length 1

◆ Any node element can also call getElementsByTagName() to get the element node of a class within it

document.getElementsByTagName(a)Copy the code

getElementsByName()

Obtain by name

document.getElementsByName(a)Copy the code

querySelector()

Gets the element ^ through the selector

The querySelector() method can only get one element on the page, or the first element if more than one element is matched

◆ querySelector() is compatible from IE8, but supports CSS3 selectors from IE9, such as nth-child(), :[SRC ^= ‘dog’] and other CSS3 selector forms are well supported

document.querySelector()       
// Internet Explorer 7 and below is not supported
Copy the code

querySelectorAll()

Gets an array of elements through a selector

◆ The querySelectorAll() method returns an array of elements via a selector

◆ Even if there is only one node matching the selector on the page, you will get an array of length 1,

document.querySelectorAll()
// Internet Explorer 7 and below is not supported
Copy the code
document.querySelectorAll("[class^='text-']") 
// Get all elements whose class begins with text
Copy the code

In our usual approach, getElementById and getElementsByName (retrieving elements through the name attribute) must start with document.

<body>
	<p>I am a paragraph</p>
    <p>I am a paragraph</p>
    <p>I am a paragraph</p>
    <p>I am a paragraph</p>
    <p>I am a paragraph</p>


    <div id="box">
        <p>1</p>
        <p>2</p>
        <p>3</p>
    </div>
	<script>
         // Get an array of p tags
        let aP = document.getElementsByTagName("p");
        console.log(aP);

        let box = document.getElementById("box");
        let box_p = box.getElementsByTagName("p");
        console.log(box_p);
    </script>
</body>
Copy the code

Get special elements

console.log (document.head);//head
console.log (document.body);//body
console.log(document.title);//// Title specifies the text of the title tag. The title can be changed by assigning
console.log(document.documentElement);//html
Copy the code
 document.title = "My modified title";
Copy the code

Delay to run

When testing DOM code, the JS code must generally be written after the HTML node, otherwise JS will not be able to find the corresponding HTML node

You can use the window.onload = function(){} event to execute the specified code after the page is loaded

<script>
    // Add the onload event listener to the window object. Onload indicates that the page is loaded
    window.onload = function () {
        // Get box 1
        let box1 = document.getElementById("box1");

        // Get box 2
        let box2 = document.getElementById("box2");
        console.log(box1);
        console.log(box2);
    }
</script>
<div id="box1"></div>
<div id="box2"></div>
Copy the code

There are three main ways to keep in mind

Get by ID

  • document.getElementById

Get nodes (list) by selector

  • document.querySelector()
  • document.querySelectorAll()

Array like object

If all the keys of an object are positive integers or zero and have the length attribute, the object is much like an array and is syntactically called an array-like object.

let obj = {
    0: 'a'.1: 'b'.2: 'c'.length: 3
};
console.log(obj[0]); // 'a'
console.log(obj[1]); // 'b'
console.log(obj.length);/ / 3
obj.push('d'); //// TypeError: obj.push is not a function

The object obj is an array-like object. However, "array-like objects" are not arrays because they do not have array-specific methods.
The object obj does not have an array push method. Using this method will result in an error.
Copy the code

The basic feature of “array-like objects” is the length attribute.

As long as you have the Length attribute, you can think of this object as resembling an array.

One problem, however, is that this length attribute is not a dynamic value and does not change as members change.

let obj = {
    length: 0
};

obj[3] = "Cloud grazing is a little sayin '.";
console.log(obj.length);

// Obj adds a numeric key, but the length property remains the same. So that tells us that OBj is not an array.
Copy the code

Typical “array-like objects”

The arguments object for the function

Most DOM element sets

string

DOM events

What is an event?

Events are specific moments of interaction that occur in a document or browser window.

For example, some actions made by users on a web page are events

DOMO level events

Syntax: ele. Event = execute script

Function: Binds events to DOM objects

Note: The execution script can be an anonymous function or a function call

Register event

Onclick Mouse click

Onmouseenter Mouse move in (only triggered once)

Onmouseleave mouse out

How to use DOM events:

<div id="Wrap"></div>

let oWrap = document.getElementById( "wrap" );

oWrap.onclick = function() {
    	// wrap What the container executes when clicked
           console.log("Clicked");
        }

oWrap.onmouseenter = function() {
            console.log("Mouse in.");
        }
Copy the code

Operation label content

How do I change the contents of an element node?

You can change the contents of an element node using two related attributes:

1) innerHTML

(2) the innerText

The innerHTML attribute sets the content of a node with HTML syntax

◆ The innerText property can only set the content of a node in plain text

<div id="Wrap"></div>

// Get the wrap node object
let oWrap = document.getElementById( "wrap" );

oWrap.innerText= 
      
  • Daiyu
  • Daiyu
"
; //innerText does not parse the tag // Most of them are strings and numbers. The numbers themselves are also converted to strings and assignedInnerText = DSB; owrap. innerText = DSB;// There is no such variable oWrap.innerHTML = "
  • Daiyu
  • < Li > Bao Chai
"
; //innerHTML parses the tag / / value console.log(oWrap.innerText); console.log(oWrap.innerHTML); Copy the code

Manipulate the CSS style of the element

External style sheets

Can not be controlled by JS, JS only has the ability to control the current HTML document, other files are not controlled

Inline style

Js can manipulate the style tag, but not often because it is difficult to control selector priority (not often)

 <style>
     #wrap{
         width: 100px;
         height: 100px;
         background-color: pink;
     }
</style>
<style id="style"></style>

<div id="wrap"></div>

<script>
    let oStyle = document.getElementById("style");

    oStyle.innerText = "#wrap{background-color:green; }" 

    oStyle.innerText = "div{background-color:green; }"
    // This cannot be modified because of the weight problem

</script>
Copy the code

Inline CSS styles

This is the way we manipulate styles by using JS

Element.style.style name =

oBox.style.color = "red";
oBox.style.backgroundColor = 'red' ; // CSS property names should be set to full hump
oBox.style.fontSize = "20px";  // Write units
oBox.style.cssFloat = "left";
// Internal or external stylesheets are not overridden
Copy the code

Manipulating element attributes

Change the legal attributes of the label

<div id="wrap"></div>

let oWrap = document.getElementById("wrap");

oWrap.title = "Here's a hint.";
console.log(oWrap.title)
console.log(oWrap.yunmu);// Only valid tag attributes are provided directly. operation
oWrap.id = "list";
oWrap.className = "box"; //class is special
Copy the code

Class: use className (recommended to use H5 new classList operation class)

Customize the operation of tag attributes

.getAttribute()

.setAttribute()

.removeAttribute()

(Can also operate legal tag attributes)

/ / get the getAttribute ()
<div id="wrap" yunmu="dsb">div</div>

console.log( oWrap.getAttribute("yunmu"));Copy the code
/ / set the setAttribute ()
oWrap.setAttribute("daiyu" , "Dai jade");
console.log(wrap);
Copy the code
/ / delete the removeAttribute ()
oWrap.removeAttribute("daiyu")
Copy the code

Custom attributes are not recommended (the same custom attributes may be added during team development)

Manipulate the class name of the element to control the CSS style

If you manipulate elements with multiple styles

#wrap{
    width: 200px;
    height: 200px;
    background-color: green;
}
<div id="wrap"></div>

let oWrap = document.getElementById("wrap");
oWrap.onclick = function(){
    oWrap.style.width = "300px";
    oWrap.style.height = "300px";
    oWrap.style.backgroundColor  = "pink";
}
/ / rewrite
oWrap.onclick = function(){
oWrap.style = "width: 300px; height:300px; background-color:purple"
   }
// String assignments to objects that do not make sense are best written to cssText
oWrap.onclick = function(){
	oWrap.style.cssText = "width:300px; height:300px; background-color:purple"
}
Copy the code

And finally we could write it as theta

#wrap.active{
            width : 300px;
             height:300px; 
             background-color:purple
        }
oWrap.onclick = function(){
           oWrap.className = "active"
        }
Copy the code

Small case (Click to expand)

#nav{
    width: 150px;
    height: 50px;
    background-color: pink;
    text-align: center;
    line-height: 50px;
    color: #fff;
    cursor: pointer;
    transition: 1s;
}
        
#nav.show{
    height: 200px;
}

<div id="nav"Text > < / div >let oNav = document.getElementById("nav");

oNav.onclick = function() {
    oNav.className = "show"
}
Copy the code

classList

<div id="wrap" class="con"></div>


let oWrap = document.getElementById("wrap");
oWrap.className = "aa bb";// adding two class names by className overwrites the original className

oWrap.className = oWrap.className + " aa bb"// This is too stiff
Copy the code

It is recommended to use the new classList in H5 instead of the className operation name

 oWrap.classList.add("aa")// Automatically handle whitespace and recognize the same class name
Copy the code

Add multiple class names

Elements. The classList. The add ()

oWrap.classList.add("aa" , "bb")
Copy the code

Remove the name of the class

Elements. The classList. Remove ()

oWrap.classList.remove("aa" , "bb")
Copy the code

The switch name

Elements. The classList. Toggle ()

(If there is a class name, add it, if there is no class name, delete it)

Two parameters are not supported

oWrap.classList.toggle("con")
Copy the code

Small case (click to expand and fold up)

<style>
    #nav{
        width: 150px;
        height: 50px;
        background-color: pink;
        text-align: center;
        line-height: 50px;
        color: #fff;
        cursor: pointer;
        transition: 1s;
    }

    #nav.show{
        height: 200px;
    }
</style>

<div id="nav">The text</div>

<script>
    let oNav = document.getElementById("nav");
    oNav.onclick = function() {
        oNav.classList.toggle("show");
    }
</script>
Copy the code

Pop-up Layer Case

<style>
#cover{
    /* display: none; * /
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0.0.0.4);
    transform: scale(0);
    transition:.6s;
    }
    #cover.show{
        transform: scale(1);
    }

    #cover.hidden{
        transform: scale(0);
    }

    #cover .content{
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        margin: auto;
        width: 200px;
        height: 80px;
        text-align: center;
        background-color: #fff;
        font-size: 14px;
        line-height: 80px;
        font-weight: bold;
    }
</style>

<body>
    <div id="btn">
        <button class="tips">The pop-up button</button>
    </div>

    <div id="cover">
        <div class="content">I'm popover content</div>   
    </div>
</body>

<script>
    let otips  = document.querySelector("#btn .tips"),
        oCover = document.querySelector("#cover");

    otips.onclick = function() {
        // oCover.style.display="block";
        oCover.classList.add("show");
    }

    oCover.onclick = function() {
        // oCover.style.display="none";
        oCover.classList.remove("show");
    }
</script>

Copy the code

This first

<div id="wrap1"</div> If clouds were once a letter in the skylet oWrap = document.getElementById("wrap1");

// The event function
oWrap.onclick = function(){
    // oWrap.style.color = "skyblue"; 

    /* The event is added to the wrap, and the event function controls the wrap*/

    this.style.color = "pink"
    // Use this keyword instead, you trigger the owRAP click event and this refers to owrap
}
Copy the code

The sample

<div id="wrap1"</div> If clouds were once a letter in the sky<div id="wrap2">If clouds were a letter to the sky</div>


let oWrap1 = document.getElementById("wrap1");
let oWrap2 = document.getElementById("wrap2");
oWrap1.onclick = function () {
    this.style.color = "pink"
}

oWrap1.onclick = function () {
    this.style.color = "pink"
}

// Use this to rewrite to
function changeColor(){
    this.style.color = "pink"
}

oWrap1.onclick = changeColor;
oWrap2.onclick = changeColor;
// The context of a function (this keyword) is determined by how the function is called. Function is a "runtime context" policy. The context of a function cannot be determined if it is not called
// Rule 1: when an object calls its method function, the context of the function is that object


// The context of the event handler is the DOM element that binds the event
Copy the code