Web API

A Web API is a set of apis (BOM and DOM) that browsers provide to manipulate browser functionality and page elements

JavaScipt consists of ECMAScript, DOM, and BOM.

  • BOM browser object model provides interactive methods and interfaces with the browser.
  • DOM document object model, which provides methods and interfaces for dealing with web page content, structure, and style;

DOM

  • DOM document object model is also known as DOM tree

  • DOM trees are made up of documents, elements, and nodes

    • Documentation: A page is a document,
    • Elements: All tags in a document are called elements. The DOM is represented by an Element
    • Nodes: Everything in the document is represented in the DOM of nodes (tags, attributes, text comments, and so on) using Node

Access to elements

All begin with document. e.g. Document.getelementbyid

Using console.dir, you can print out the returned element object for a better view of the properties and methods

GetElementById (Element ID)

  • Gets the element labeled Id (the Id value in the document is unique; there are no duplicate ids)

  • Parameter: ID value, case sensitive string

  • Returns the object corresponding to the element node of the id attribute value

    <body>
        <div id="time">The 2019-9-9</div>
        <script>
            // Since our document page loads from the top down, we need to have tags first, so we write our script below the tags
            var timer = document.getElementById('time');
            console.log(timer);
            console.log(typeof timer);
            // console.dir prints the element object we return for a better view of its properties and methods
            console.dir(timer);
        </script>
    </body>
    Copy the code

getElementsByTagName

Note: The result is an array of objects. To manipulate elements, you need to traverse the pseudo-array and the pseudo-array cannot use array methods

  • Get the element by the tag name

  • Parameter: Label name

  • Returns an array of objects (pseudo-array)

    <body>
        <ul id="nav">
             <li>Rarely used word</li>
             <li>Rarely used word</li>
             <li>Rarely used word</li>
             <li>Rarely used word</li>
             <li>Rarely used word</li>
         </ul>
         <script>
                // 1. Returns a collection of retrieved elements stored as a pseudo-array
                var lis = document.getElementsByTagName('li');
                console.log(lis);
                console.log(lis[0]);
                // 2. We want to print the elements in sequence
                for (var i = 0; i < lis.length; i++) {
                    console.log(lis[i]);
                }
                / / 3. Element. GetElementsByTagName () can get certain tags within the element
                var nav = document.getElementById('nav'); // This gets the nav element
                var navLis = nav.getElementsByTagName('li');
                console.log(navLis);
        </script>
    <body>
    Copy the code

    Note that getElementsByTagName() is retrieved as a dynamic collection, that is, when the page adds tags, elements are added to the collection.

GetElementsByCalssName (Class name)

  • Gets the element by the class name

  • Parameter calss class name

  • Returns a collection of element objects with the corresponding class name

    <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>
         //getElementsByClassName gets some set of elements based on the class name
        var boxs=document.getElementsByClassName("box")
        console.log(boxs)
        <script>
     <body>
    Copy the code

querySelector

  • It can be any selector such as ID, tag name, or class name

  • Parameters: can be id, class name, label selector

  • Returns: the first element that the pattern matches

  • Note: you need to prefix the selector with symbols such as. Box and #nav. Let the querySelector know what selector it is so it adds a sign. It’s different from the previous ones

      <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>
        // 2. QuerySelector returns the first element of the specified selector object. Remember that the selector needs to be marked
            var firstBox = document.querySelector('.box'); / / the class name of the class
            console.log(firstBox);
            var nav = document.querySelector('#nav'); //id
            console.log(nav);
            var li = document.querySelector('li');/ / label
            console.log(li);
        <script>
     <body>
    Copy the code

querySelectorAll

  • It can be any selector such as ID, tag name, or class name

  • Parameters: can be id, class name, label selector

  • Returns: collection of all element objects (pseudo-array) matched by this pattern

      <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>
       // 3. querySelectorAll() returns a collection of all element objects for the specified selector
            var allBox = document.querySelectorAll('.box');
            console.log(allBox);
            var lis = document.querySelectorAll('li');
            console.log(lis);
        <script>
     <body>
    Copy the code

Get special elements (body, HTML)

  • Get body: document.body

  • Get HTML: document.documentElement

Gets the node of the element

All content in a page is a node, and nodes are represented by nodes

  • DOM trees can divide nodes into different hierarchies, and the most common one is the father-son and brother-son hierarchies

The parent node

  • ParentNode // Node indicates a node
  • ParentNode // returns the parentNode of a nodeThe parent of the most recent level
  • Returns NULL if the specified node has no parent
    <div class="demo">
        <div class="box">
            <span class="erweima">x</span>
        </div>
    </div>
    <script>
        // 1. ParentNode parentNode
        var erweima = document.querySelector('.erweima');
        // var box = document.querySelector('.box');
        // Return null if the parent node is not found
        console.log(erweima.parentNode);
    </script>
Copy the code

Child element node

  • Parentnode. children (supported by all browsers) (does not include element nodes, text nodes, etc.)

  • ParentNode firstElementChild () for the first element node has the compatibility ie 9 to support

  • ParentNode. LastElementChild (access to the last child node) is compatible with ie 9 to support problem

  • Parentnode.children [0] (no compatibility issues and returns first child)

        <ul> 
            <li>I'm li</li>
            <li>I'm li</li>
            <li>I'm li</li>
            <li>I'm li</li>
        </ul>
        <script>
        // 2. Children get all child element nodes (excluding text nodes, etc.)
            console.log(ul.children);
       //2. FirstElementChild gets the first child node only supported in IE9
           console.log(ul.firstElementChild)
       //3. LastElementChild gets the last child node, which is supported only in IE9
           console.log(ul.lastElementChild)
       //4.children[0] is often used in development with no compatibility problems and returns the first child
           console.log(ul.children[0])
           console.log(ul.children[children.length-1])
        </script>
    Copy the code

Brother nodes

  • Node. nexElementSibling // Returns the next sibling node of the current element, or null if not found

  • Node. PreviousElementSibling / / return the current element nodes on a brother, I couldn’t find it returns null

  • Both methods have compatibility issues and are supported by IE9 above

    < div > I am a div < / div ><span>I am a span</span>
        <script>
            var div = document.querySelector('div');
            var span=documnet.querySelector("span")
         // 1. NextElementSibling get the next sibling node
            console.log(div.nextElementSibling);
         // 2. NextElementSibling get the last sibling node
            console.log(span.previousElementSibling);
        </script>
    Copy the code

    Q: Resolve compatibility issues

    A: Encapsulate a compatibility function yourself

       function getNextElementSibling(element) {
          var el = element;
          while (el = el.nextSibling) {
            if (el.nodeType === 1) {
                returnel; }}return null;
        }  
    Copy the code

The event processing

JavaScript program is used in the asynchronous event processing model, event processing is divided into three parts.

  • Event source (on which element or tag)

  • Event types (e.g. mouse click, double click, pass, keyboard key press)

  • Handler (refers to the browser calling the corresponding handler (in the form of a function) after the event is triggered, also known as an event handler)

    <body>
     <div>The event processing<div>
     <script>
     //1. Obtain event sources
     var div=document.querySelector("div") 
    // 2. Bind events register events
      div.onclick
     //3. Add event handlers
      div.onclick=function(){
         console.log("我")
      }
      <script>
    <body>
    Copy the code

Register event

There are three ways to register an event

  • Registration using HTML tag attributes (for example, event registration for Vue)

  • Using the traditional DOM object registration (onclick) is unique

    Note: Only one event source can be registered in this way. If multiple events are registered, the later ones override the previous ones

  • Use the addEventListener (type,listener,useCapture) method to listen for the registration method (you can add multiple events or cancel events).

    • Type: indicates the event type, for example, click and mouseoverPay attention toYou don’t need on in this
    • Listener: An event handler that is called when an event occurs
    • UseCapture: Optional, a Boolean value, false by default. (False: capture phase, true: bubble phase)

    Note: The addEventListener() method does not support earlier versions of IE

    <body> <div onClick=show()> Three ways to register an event <div> <script> //1. Function show(){alert("div was clicked ")} //2 Var div=document.querySelector("div") // Note that the event type starts with on and the corresponding event name is lowercase div.onclick = function(){ Alert ("DOM register div")} //3. Var div=document.querySelector("div") // Add the event div.adDeventListener ('click',()=>{ Div. RemoveEventListener ("click",()=>{alert(" remove Div event ")}) <script> <body>Copy the code

Delete event (unbind event)

  1. Remove the traditional registration method (DOM object method)
    • div.onclick=null;
  2. Way to remove listening events (cannot be removed using anonymous functions)
    • div.removeEventListener (type,listener,useCapture);
<body>   
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <script>
        var divs = document.querySelectorAll('div');
        divs[0].onclick = function() {
            alert(11);
    // 1. Delete events in the traditional way
            divs[0].onclick = null;
        }
    // 2. RemoveEventListener Deletes the event
        divs[1].addEventListener('click', fn) // Fn inside does not need to be called with parentheses
        function fn() {
            alert(22);
            divs[1].removeEventListener('click', fn);
        }
       
    </script>
<body>
Copy the code

Mouse events

  • The execution order of mouse events

​ mousedown->mouseup->click->mousedown->mouseup->click->dbclick

Mouse events describe
click Click the left mouse button and release the trigger
dbclick Triggered when you double-click the left mouse button
mousedown Triggered when the mouse button is pressed
mouseup Triggered when the mouse button is released
mouseover Triggered when the mouse passes overHas event bubbling
mouseout Triggered when the mouse is awayHas event bubbling
mouseenter Triggered when the mouse passes overNo event bubbling
mouseleave Triggered when the mouse passes overNo event bubbling
mousemove Triggered when mouse is moved
contextmenu Disable the right mouse button menu
selectstart Disable mouse selection of text

Click events can only be triggered if mouseover and Mouseup events are triggered sequentially on the same element

A DBClick event is emitted only if two more click events are emitted

  • The difference between mouseEnter and Mouseove

    • Mouseenter is often used in conjunction with mouseleave
    //1. Mouseenter has no event bubbling and will not be passed to son click events
       <div class="father">
            <div class="son"></div>
        </div>
    <script>
            var father = document.querySelector('.father');
            var son = document.querySelector('.son');
            father.addEventListener('mouseenter'.function() {
                console.log(11);
    
            })
     </script>
    Copy the code
  • Disable the right mouse button menu

    //1. Contextmenu disables the right mouse button menu
    documnet.addEventListener("contextmenu".function(e){
     e.preventDefault(); // Prevents the default jump behavior of the event
    })
    Copy the code
  • Disable mouse selection of text

    //2. Selectstart disables mouse selection of text
    documnet.addEventListener("selectstart".function(e){
       e.preventDefault(); // Prevents the default jump behavior of the event
    })
    Copy the code

“Event”

Mous focus event describe
blur Triggered when an element loses focus, it does not bubble
focus Triggered when the element gains focus, no bubbles

Keyboard events

General keyboard events are used in input box labels

  • Execution order when the character key is pressed (three events are triggered when the character key is pressed)

    Keydown -> keyPress -> keyUP where keyDown and keypress are fired before the file box changes, and then the keyup event is fired after the file box changes

  • Order of execution when a non-character key is pressed (a secondary event is triggered when a non-character key is pressed)

    Keydown -> keyUP Where keyDown is triggered first and keyUp is triggered last.

  • Note: KeyDown and KeyPress in a text box feature: the handler that executes the event first drops text into the text box

  • Keyup in the text box features: first text into the text box before the execution of the event handler

Keyboard events describe
keydown Press any key on the keyboard to trigger; Hold and repeat
keypress Press the character key on the keyboard to trigger; Hold it down, trigger it repeatedly,Do not recognize function keys such as arrow, CTRL, Shift, etc
keyup Triggered when a key on the keyboard is released
e.keyCode Retrieves the key when the user presses itASCII code
e.key Gets the name when the user presses the key
<script>
        // Common keyboard events
        //1. Trigger when the keyUp button is pressed
        document.addEventListener('keyup'.function() {
            console.log('I bounced.');
        })

        //3. When the keyPress button is pressed, it triggers unrecognized function keys such as CTRL/SHIFT left and right arrows
        document.addEventListener('keypress'.function() {
                console.log('I pressed press');
        })
        //2. When the keyDown button is pressed, it triggers function keys such as CTRL/SHIFT left/right arrows
        document.addEventListener('keydown'.function() {
                console.log('I pressed down');
        })
        Keydown -- keypress -- keyup

       // 5. Use the ASCII code value returned by Keycode to determine which key the user pressed
        document.addEventListener("keyup".function(e){
             if(e.keyCode===65){
               alert("You pressed the A key.")}else{
               alert("You didn't press the A button.")
             }
         })
</script>
Copy the code

Scrollbar event

When the scroll bar appears and the page is rolled down, the height above is hidden, which is called the part of the page being rolled out. At this time, the scroll bar will trigger the Scroll event when it is rolled

element.addEventListener("scroll".() = >{
    console.log(element.scrollTop)
})
Copy the code

Form events

The change event is emitted when the value of the form changes

The event object

When an event on the DOM is triggered, an event object is generated, which contains all the information related to the event. This includes the element that caused the event, the type of event, and other information related to a particular event.

  • When an event is triggered, the system generates an event object and passes it as an argument to the event handler

  • Declare a parameter in an event handler to receive event parameters.

    / / 1. Method a
    eventTarget.onclick=function(event){
    // The event is the event object, which we prefer to write as e or evt
    }
    
    // 2
    
    eventTarget.addEventListener("click",function(event){
     // The event is the event object, we also like to write e or evt/ this one
    })
    
    	/ / 3. The method 3
     eventTarget.addEventListener("click",fn)
      function(event){
      // The event is the event object, which we like to write as e or evt
    }
     
    Copy the code

Properties and methods of the event object

Properties and methods of the event object instructions
e.target returnThe triggerObject standards for events
e.srcElement returnThe triggerThe object of the event is not standardie6-8
e.type Event-returningtypeFor example, click Mouseover does not have on
e.canceIBubble This property prevents bubbles from being non-standardie6-8use
e.returnValue This property prevents default events (default behavior) from being non-standardie6-8Use things like don’t let links jump
e.preventDefault() This method prevents default event (default behavior) standards such as not allowing links to jump
e.stopPropagation() Standard prevents events from bubbling

The difference between this and E.target of the event object

  • This refers to the element bound to the event

  • E.target refers to the event trigger element and don’t forget e.

    In general, e.target and this refer to the same thing

    However, there is a different case, which is when the event bubbles (the parent element has the same event, click the child element, the parent element’s event handler is also triggered).

    In this case, this refers to the element, because this makes the final reference to the element bound to the event

    Target points to the child element because target makes the end point to the element that the event fires

    <div>123</div>
    <ul>
        <li>abc</li>
        <li>abc</li>
        <li>abc</li>
    </ul>
     <script>
   1. // Target is the same as this
        var div = document.querySelector('div');
        div.addEventListener('click'.function(e) {
            // e.target and this refer to divs
            console.log(e.target);
            console.log(this);
        });
   2. // In the bubbling case target and this point to different things
     var ul=document.querySelector("ul")
      ul.addEventListener("click".function(){
         // we bind the event to ul so this points to ul
              console.log(this);  // ul
              // e.target is the object that triggered the event. We clicked on Li
              console.log(e.target);  // li
})
    </script>
Copy the code

Mouse event object

Mouse event object instructions
e.clientX Returns the viewable area of the mouse relative to the browser windowXcoordinates
e.clientY Returns the viewable area of the mouse relative to the browser windowYcoordinates
e.pageX Returns the mouse pointer relative to the document pageXCoordinates IE9+ support
e.pageY Returns the mouse pointer relative to the document pageYCoordinates IE9+ support
e.screenX Returns the x-coordinate of the mouse relative to the computer screen
e.screenY Returns the Y coordinate of the mouse relative to the computer screen
    <script>
        // the MouseEvent object MouseEvent
        document.addEventListener('click'.function(e) {
            // 1. The client mouse is in view of the x and Y coordinates
            console.log(e.clientX);
            console.log(e.clientY);
            console.log('-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -');

            // 2. Page Indicates the x and Y coordinates of the page document
            console.log(e.pageX);
            console.log(e.pageY);
            console.log('-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -');

            // 3. The mouse is in the x and Y coordinates of the computer screen
            console.log(e.screenX);
            console.log(e.screenY);

        })
    </script>
Copy the code

Operating elements

Modifying element content

Personal recommendation: Use innerHTML a lot

  • Element.innerText

    Display only plain text, remove HTML tags, and remove whitespace and newlines

  • Element.innerHTML

    Displays the entire content of the specified element, including the HTML tag, with Spaces and newlines reserved

  • InnerText differs from innerHTML

    • Use the innerTextAccess to content Don't recognizeHTML tags, Spaces and line feeds
    • Use the innerTextSet the content Don't recognizeHTML tags
    • Get the content with innerHTMLidentifyAll content includes HTML tags, with Spaces and line breaks reserved
    • Set the content with innerHTMLidentifyThe HTML tag can be set
	<body>
    <button>Displays the current system time</button>
    <div>A certain time</div>
    <p>1123</p>
    <script>
        // When we click the button, the text inside the div will change
        // 1. Get the element
        var btn = document.querySelector('button');
        var div = document.querySelector('div');
        // 2. Register events
        btn.onclick = function() {
            // div.innerText = '2021-6-18';
            div.innerHTML = getDate();
        }
        function getDate() {
            var date = new Date(a);// Let's write a date for Wednesday, May 1st, 2019
            var year = date.getFullYear();
            var month = date.getMonth() + 1;
            var dates = date.getDate();
            var arr = ['Sunday'.'Monday'.'Tuesday'.'Wednesday'.'Thursday'.'Friday'.'Saturday'];
            var day = date.getDay();
            return 'Today is:' + year + 'years' + month + 'month' + dates + 'day' + arr[day];
        }
    </script>
</body>
Copy the code

Operations on properties

This refers to the caller of the event function

  • Attribute operations on ordinary elements

  • Attribute operations on form elements

  • Gets the value of the property

    Element object. Attribute name

  • Sets the value of the property

    Element object. Attribute name = value

    <body>
        <button>button</button>
        <input type="text" value="Input content">
        <script>
            // 1. Get the element
            var btn = document.querySelector('button');
            var input = document.querySelector('input');
            // 2. Register event handlers
            btn.onclick = function() {
                // The value text in the form is modified by value
                input.value = 'Clicked';
                // If you want a form to be disabled, you can't click Disabled. We want the button to be disabled
                // btn.disabled = true;
                this.disabled = true;
                // This refers to the caller of the event function BTN
            }
        </script>
    </body>
    Copy the code

Style property operations

Modify element size, color, position and other modes through JS

Commonly used way

  • Element.style. style = value // Inline style operation changes the inline style weight to be higher

  • Element.className= “className” // className style operation overrides the original className

    • Element.className= “” // an empty or null value nulls the className of the Element
  • Element.classlist. add (” class name “) // The Add class name operation can add more than one class name without overwriting the original one

    • Element.classlist. remove(” Remove class name “) // Remove class name operationMultiple class names can be removed
    • Element.classlist. toggle(” Toggle the class name “) // Toggle the class name if there is none to add, if there is none to remove
    • Element. CalssList. The contains (” class “) / / contains such a name,Returns a Boolean valueCheck whether it exists

    CalssName is a reserved word, so calssName is used to manipulate the element class name attribute

    <body>
        <div></div>
        <script>
            // 1. Get the element
            var div = document.querySelector('div');
            // 2. Register event handlers
            div.onclick = function() {
                // Div. Style attributes are case sensitive in js with hump naming
                this.style.backgroundColor = 'purple';
                // Don't forget to add px
                this.style.width = '250px';
     // 2. We can change the style of an element by changing its className
       // 3. If we want to keep the original class name, we can do this with multiple class name selectors
       // this.className = 'change';
                this.className = 'first change';
            }
        </script>
    </body>
    Copy the code

Cancel the default jump for the A tag

  • Method 1: Add return false at the end of the handler;

  • Method 2: add javascript to a tag :;

    // Set return false at the end of the handler;
    
    <body>
    <a id="link" href="https://www.baidu.com">Click on the</a>
    // Set the href value of the a tag to: javascript:
     <a href="javascript:;">Click on the 2</a>
    
    <script>
        var link = document.getElementById('link');
        link.onclick = function(){
        alert('hello');
        // Method 1: cancel the default jump behavior after a clicks return false;
        return false;
        };
    </script>
    <body>
    
    // Set the href value of the a tag to: javascript:;
     <a href="javascript:;">Click on the 2</a>
    / / note:
    // Set the herf value of the a tag to javascript:, which means that when a is clicked in the future, the default jump behavior will be blocked and only js code will be executed
    
    
    Copy the code

All cases: all

    <script>
        // 1. Select all and deselect all: Let the checked properties of all the following check boxes follow the select all button
        // Get the element
        
        var j_cbAll = document.getElementById('j_cbAll'); 
        var j_tbs = document.getElementById('j_tb').getElementsByTagName('input'); 
        // Select all button to register events
        j_cbAll.onclick = function() {
                // this.checked Indicates the checked status of the current check box
                console.log(this.checked);
                for (var i = 0; i < j_tbs.length; i++) {
                    j_tbs[i].checked = this.checked; }}// Register click events for all subcheckboxes
        for (var i = 0; i < j_tbs.length; i++) {
            j_tbs[i].onclick = function() {
                // flag Controls whether the all button is selected
                var flag = true;
                // Each time you click the check box below, loop to check whether all four small buttons are selected
                for (var i = 0; i < j_tbs.length; i++) {
                    if(! j_tbs[i].checked) { flag =false;
                        break; }}// Set the status of the all button
                j_cbAll.checked = flag;
            }
        }
    </script>
Copy the code

Custom property operations

Why custom properties: to store data in a page rather than in a database

Get property values

  • Element. attribute (access to Element attributes via built-in attributes)
  • Element.getattribute (” attribute “) (generally used for custom attributes)Compatibility Acquisition
    <div id="demo" index="1" class="nav"></div>
    <script>
        var div = document.querySelector('div');
  // 1. Get the attribute value of the element
        // (1) element
       console.log(div.id);
  //(2) element.getAttribute(' attribute ') get getAttribute(' attribute '
        console.log(div.getAttribute('id'));
        console.log(div.getAttribute('index'));
	</script>
Copy the code

Setting property values

  • Element. property = “value” (built-in property)
  • Element.setattribute (” Attribute, “” value”); // Generally used for custom attributes
   // 2. Set element attribute values
        // (1) element. attribute = 'value'
        div.id = 'test';
        div.className = 'navs';
   // (2) element.setAttribute(' attribute ', 'value '); This applies primarily to custom attributes
        div.setAttribute('index'.2);
        div.setAttribute('class'.'footer'); // the class is special
Copy the code

Remove attribute values

  • Element. RemoveAttribute (” property “)
// Class is not className
// 3 removeAttribute removeAttribute
div.removeAttribute('index');
Copy the code

Gets H5 custom attributes

  • You can only get custom properties that start with data

  • Element.dataset. Index or element. dataset[” index “] IE11 only supports this feature

    Using the element.dataset. Property yields a custom collection of properties starting with data-

Set H5 custom properties

H5 specifies that a custom attribute name begins with data- and is assigned.

  • Set element. setAttribute(” data-index “,2) with js

        <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 can only get custom attributes starting with data-
    // Dataset is a collection containing all the custom attributes starting with data
            console.log(div.dataset);
            console.log(div.dataset.index);
            console.log(div.dataset['index']);
    // If there are more than one - linked word in the custom attribute, we use the camel name when we get it
            console.log(div.dataset.listName);
            console.log(div.dataset['listName']);
        </script>
    Copy the code

Tab bar Example: Tab bar

    <script>
        // Get the element
        var tab_list = document.querySelector('.tab_list');
        var lis = tab_list.querySelectorAll('li');
        var items = document.querySelectorAll('.item');
        // For loop, bind TAB click events
        for (var i = 0; i < lis.length; i++) {
            // Start setting index numbers for 5 li's
            lis[i].setAttribute('index', i);
            lis[i].onclick = function() {
                // 1. The current base color will be red and the rest will remain unchanged.
                // Clean up the rest of the class
                for (var i = 0; i < lis.length; i++) {
                    lis[i].className = ' ';
                }
                Leave me alone
                this.className = 'current';
                // 2. Display the content module below
                var index = this.getAttribute('index');
                console.log(index);
                // Kill everyone and hide the rest of the items
                for (var i = 0; i < items.length; i++) {
                    items[i].style.display = 'none';
                }
                // Leave me to display the corresponding item
                items[index].style.display = 'block';
            }
        }
    </script>
Copy the code

Node operation

Node indicates the parent and child indicates the child

Create a node

  • Document. The createElement method (” tag “)
    • Dynamically created elements need to be added after they are created

Add a node

  • Node. appendChild (child) // Node: parent child: child

    • Adds a node to the list of children of the parent node represented by nodeAt the end of, the array-like method push
  • Node. insertBefore(child, specify the location of the node)

    • Adds a node to the ~ of the specified child node of the parent node represented by nodeIn front of the, similar to the before element in CSS
    <body>   
        <ul>
            <li>123</li>
        </ul>
        <script>
         // 1. Create a node element node
            var li = document.createElement('li');
         Node. appendChild(child) Node's parent child is the append element after the child
            var ul = document.querySelector('ul');
            ul.appendChild(li);
         // 3. Add node node.insertbefore (child, specify element);
            var lili = document.createElement('li');
            ul.insertBefore(lili, ul.children[0]);
            // 4. We want to add a new element to the page: 1. Add elements
        </script>
    </body>
    Copy the code

Remove nodes

  • The node.removechild (Child) method removes a child node from the parent node and returns the deleted node

    <body>  
       <button>delete</button>
        <ul>
            <li>Big bear</li>
            <li>Two bears</li>
            <li>Baldheaded stronger</li>
        </ul>
        <script>
            // 1. Get the element
            var ul = document.querySelector('ul');
            var btn = document.querySelector('button');
            // 2. Remove element node.removechild (child)
            // ul.removeChild(ul.children[0]);
            // 3. Click the button to delete the children in turn
            btn.onclick = function() {
                if (ul.children.length == 0) {
                    this.disabled = true;
                } else {
                    ul.removeChild(ul.children[0]); }}</script>
    </body>
    Copy the code

Copy (clone) the node

  • Node.clonenode () // Returns a copy of the node on which the method was called, also known as a clone/copy node

  • If the parenthesis argument is empty or false, it is a shallow copy, that is, only the replicated node itself is cloned, not its children

  • If the parenthesis argument is true, it is a deep copy, copying the node itself and all its children

    <body>  
        <ul> 
            <li>1111</li>
            <li>2</li>
            <li>3</li>
        </ul>
        <script>
            var ul = document.querySelector('ul');
         // 1. node.cloneNode(); The parentheses are empty or the inside is false. Shallow copy copies only the tag, not the inside
        // 2. node.cloneNode(true); The parentheses are true. The deep copy copy tag copies the contents inside
            var lili = ul.children[0].cloneNode(true);
            ul.appendChild(lili);
        </script>
    </body>
    Copy the code

Core summary of DOM

DOM manipulation, we’re dealing with elements. There are mainly create, add, delete, change, check.

Three ways to create an element

  • document.write()
  • Element. InnerHTML = value
  • document.createElement()

InnerHTML array method (efficient)

<script>
    function fn() {
        var d1 = +new Date(a);var array = [];
        for (var i = 0; i < 1000; i++) {
        // Add labels to the end using the array method push
array.push('
      
'
); } document.body.innerHTML = array.join(' '); var d2 = +new Date(a);console.log(d2 - d1); } fn(); </script> Copy the code

add

  • AppendChild // Adds a node at the end of the parent node
  • InsertBefore // You can specify where to add child nodes

delete

  • removeChild

change

  • Mainly modify DOM element attributes, CONTENT of DOM elements, attributes, form values and so on.
  • Modify element attributes: SRC, href, title, etc
  • Modify the normal contents of the element: innerHMTL, innerText
  • Modify form elements: Value, Type, disabled, etc
  • Modify the element’s mode, style, className

check

  • The API provided by DOM: getElementById, getElementByTagName The older usage is not recommended
  • H5 provides new methods: querySelector querySelectorAll advocates
  • Use node operations to get elements: parentNode, children, siblings (previousElementSibling, nextElementSibling) advocacy

Manipulate custom properties

  • The main operation is custom properties
  • SetAttribute: Sets a custom attribute
  • GetAttribute: Obtains a custom attribute
  • RemoveAttribute: Removes an attribute

Native JS (BOM operation) ->.

DOM event flow ->.

“Likes, favorites and comments”

❤️ follow + like + favorites + comments + forward ❤️, encourage the author to create a better article, thank 🙏 everyone.