Learning notes webapi_ one

Posted by aclees86 on Fri, 07 Jan 2022 11:12:19 +0100

Web APIs

Web API introduction

1. Concept of API

API (Application Programming Interface) is some pre-defined functions, which aims to provide the ability for applications and developers to access a group of routines based on some software or hardware without accessing the source code and understanding the details of its internal working mechanism.

Give an example to explain what an API is.

For example,

​ There is a function fopen() in C language that can open files on the hard disk. For us, this function is a tool for opening files provided by C language.

​ There is a function alert() in javascript that can pop up a prompt box on the page. This function is a pop-up box tool provided by js.

These tools (functions) are provided by the programming language, and the internal implementation has been encapsulated. We just need to learn to use these tools flexibly.

2. Concept of Web API

​ Web API is a set of APIs (BOM and DOM) provided by the browser to operate browser functions and page elements.

​ At this stage, we mainly explain the common API s for browsers, and mainly do interactive effects for browsers. For example, we want to pop up a warning box in the browser and directly use alert('pop up ')

​ MDN detailed API: https://developer.mozilla.org/zh-CN/docs/Web/API

​ Because there are many Web APIs, we call this stage Web APIs.

​ The Web API here specifically refers to a series of APIs (many functions or object methods) provided by the browser, that is, a series of tools for operating web pages. For example, methods of operating html tags and page addresses.

3. API and web API summary

  1. API is an interface provided for our programmers to help us realize certain functions. We can use it without worrying about how to implement it internally
  2. Web API is mainly aimed at the interface provided by the browser, and mainly aims at the interactive effect of the browser.
  3. Web API s generally have inputs and outputs (function parameters and return values), and many web APIs are methods (functions)
  4. Learning Web API can be combined with the previous idea of learning built-in object methods

DOM introduction

1. What is DOM

​ The Document Object Model (DOM) is W3C Treatment recommended by the organization Extensible markup language (html or xhtml) standard Programming interface.

​ W3C has defined a series of DOM interfaces, which can change the content, structure and style of web pages.

DOM is a set of specifications for processing html and xml documents formulated by W3C organization. All browsers follow this set of standards.

2. DOM tree

DOM tree, also known as document tree model, maps the document into a tree structure, processes it through node objects, and the processing results can be added to the current page.

  • Document: a page is a document, which is represented by document in DOM
  • Node: all contents in the web page are nodes (labels, attributes, text, notes, etc.) in the document tree, which are represented by node
  • Tag node: all tags in a web page are usually called element nodes, also referred to as "elements", which are represented by element

Get element

Why get page elements?

For example, if we want to operate a part (show / hide, animation) on the page, we need to obtain the corresponding element of the part before operating it.

1. Get by ID

Syntax:document.getElementById(id)
Function: according to ID Get element object
Parameters: id Value, case sensitive string
Return value: element object or null

Case code

<body>
    <div id="time">2019-9-9</div>
    <script>
        //Because we load the document page from top to bottom, we have to have a label first, so we write the script below the label
        var timer = document.getElementById('time');
        console.log(timer);
        console.log(typeof timer);
        // console.dir print the element object we returned, and dir better view the properties and methods inside
        console.dir(timer);
    
</script>

</body>

2. Get the element according to the tag name

Syntax: document.getElementsByTagName('Tag name') perhaps element.getElementsByTagName('Tag name'
Function: get the element object according to the tag name
Parameters: tag names
Return value: collection of element objects (pseudo array, array elements are element objects)

Case code

<body>
    <ul>
        <li>Know or not know or not, should be waiting for you for a long time 11</li>
        <li>Know or not know or not, should be waiting for you for a long time 22</li>
        <li>Do you know, I should have been waiting for you for a long time 33</li>
        <li>Know or not know or not, should be waiting for you for a long time 44</li>
        <li>Know or not know or not, should be waiting for you for a long time 55</li>
    </ul>

    <ul id="nav">
        <li>Rare words</li>
        <li>Rare words</li>
        <li>Rare words</li>
        <li>Rare words</li>
        <li>Rare words</li>
    </ul>

    <script>
        // 1. What is returned is a collection of elements and objects that are retrieved and stored in the form of pseudo arrays
        var lis = document.getElementsByTagName('li');
        console.log(lis);
        console.log(lis[0]);
        // 2. We want to print the element objects in turn. We can traverse them
        for (var i = 0; i < lis.length; i++) {
            console.log(lis[i]);
        }
        // 3.  element.getElementsByTagName() can get some tags in this element
        var nav = document.getElementById('nav'); //This gets the nav} element
        var navLis = nav.getElementsByTagName('li');
        console.log(navLis);
    
</script>

</body>

Note: getElementsByTagName() obtains a dynamic collection, that is, when a tag is added to the page, elements are added to the collection.

3. H5 new element acquisition method

Case code

<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>
        // 1. getElementsByClassName:: get some element collections according to the class name
        var boxs = document.getElementsByClassName('box');
        console.log(boxs);
        // 2. querySelector , returns the first element object of the specified selector , remember that the selector in , needs to be signed box  #nav
        var firstBox = document.querySelector('.box');
        console.log(firstBox);
        var nav = document.querySelector('#nav');
        console.log(nav);
        var li = document.querySelector('li');
        console.log(li);
        // 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>

Event basis

1. Event overview

JavaScript enables us to create dynamic pages, and events are behaviors that can be detected by JavaScript.

Simple understanding: trigger response mechanism.

​ Each element in the web page can generate some events that can trigger JavaScript. For example, we can generate an event when the user clicks a button, and then perform some operations.

2. Three elements of event

  • Event source (who): the element that triggers the event
  • Event type (what event): for example, click event
  • Event handler (what to do): code to be executed after the event is triggered (function form), event handler

Case code

<body>
    <button id="btn">Tang Bohu</button>
    <script>
        //Click a button to pop up a dialog box
        // 1. Event is composed of three parts: event source, event type, event handler, which is also called event three elements
        //(1) Event source: the object to which the event is triggered; who is the button
        var btn = document.getElementById('btn');
        //(2) Event type  how to trigger  what event  such as mouse click or mouse pass  or keyboard press
        //(3) The event handler {is completed by a function assignment
        btn.onclick = function({
            alert('Point Qiuxiang');
        }
    
</script>

</body>

3. Steps to execute the event

Case code

<body>
    <div>123</div>
    <script>
        //Perform event steps
        //Click div # console output # I'm selected
        // 1. Get event source
        var div = document.querySelector('div');
        // 2. Bind event} register event
        // div.onclick 
        // 3. Add event handler
        div.onclick = function({
            console.log('I was chosen');
        }
    
</script>

</body>

Operation element

​ The DOM operation of JavaScript can change the content, structure and style of web pages. We can use DOM operation elements to change the content and attributes of elements. (Note: these operations are implemented through the attributes of the element object)

1. Change element content (get or set)

innerText change element content

<body>
    <button>Displays the current system time</button>
    <div>At a certain time</div>
    <p>1123</p>
    <script>
        //When we click the button, the text in div will change
        // 1. Get element
        var btn = document.querySelector('button');
        var div = document.querySelector('div');
        // 2. Registration event
        btn.onclick = function({
            // div.innerText = '2019-6-6';
            div.innerHTML = getDate();
        }
        function getDate({
            var date = new Date();
            //Let's write a Wednesday, May 1, 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 + 'year' + month + 'month' + dates + 'day ' + arr[day];
        }
    
</script>

</body>

The difference between innerText and innerHTML

  • Differences in obtaining content:

​ innerText removes spaces and line breaks, while innerHTML retains spaces and line breaks

  • Differences in setting content:

​ innerText does not recognize html, but innerHTML does

Case code

<body>
    <div></div>
    <p>
        I am writing
        <span>123</span>
    </p>

    <script>
        //The difference between innerText and innerHTML
        // 1. innerText , does not recognize html tags , non standard , removes spaces and line breaks
        var div = document.querySelector('div');
        //div.innerText = '< strong > today is: < / strong > 2019';
        // 2. innerHTML , identify html tags , W3C standard , retain spaces and line breaks
        div.innerHTML = '<strong>Today is:</strong> 2019';
        //These two properties are readable and writable, and you can get the contents of the element
        var p = document.querySelector('p');
        console.log(p.innerText);
        console.log(p.innerHTML);
    
</script>

</body>

2. Style attribute operation

We can modify the size, color, position and other styles of elements through JS.

Method 1: by operating the style attribute

The style attribute of the element object is also an object!

Element object style. Style attribute = value;

Case code

<body>
    <div></div>
    <script>
        // 1. Get element
        var div = document.querySelector('div');
        // 2. Register event} handlers
        div.onclick = function({
            //The attribute} in div.style adopts hump naming method
            this.style.backgroundColor = 'purple';
            this.style.width = '250px';
        }
    
</script>

</body>

Method 2: operate the className attribute

Element object className = value;

Because class is a keyword, all use className.

Case code

<body>
    <div class="first">text</div>
    <script>
        // 1. Use element Style , get and modify the element style , if there are few styles , or , use it when the function is simple
        var test = document.querySelector('div');
        test.onclick = function({
            // this.style.backgroundColor = 'purple';
            // this.style.color = '#fff';
            // this.style.fontSize = '25px';
            // this.style.marginTop = '100px';

            // 2. We can change the style of an element by {modifying its className} which is suitable for situations with many styles or complex functions
            // 3. If we want to keep the original class name, we can do this: multiple class name selectors
            // this.className = 'change';
            this.className = 'first change';
        }
    
</script>

</body>

Exclusive operation

1. Exclusivity

If there is the same group of elements, we need to use the exclusive idea algorithm of loop if we want an element to implement a certain style:

  1. Clear all elements (kill others)
  2. Style the current element (leave me alone)
  3. Note that the order cannot be reversed. Kill others first, and then set yourself
    <button>Button1</button>
    <button>Button 2</
button>
    <button>Button 3</button>
    <button>Button 4</button>
    <button>Button 5</button>
    <script>
        // 1. Get all button elements
        var btns = document.getElementsByTagName('button');
        //btns gets every element in the pseudo array btns[i]
        for (var i = 0; i < btns.length; i++) {
            btns[i].onclick = function({
                //(1) let's remove the background color of all buttons and kill everyone
                for (var i = 0; i < btns.length; i++) {
                    btns[i].style.backgroundColor = '';
                }
                //(2) then let the current element background color be pink , and leave me
                this.style.backgroundColor = 'pink';

            }
        }
    
</script>

Case: Baidu skin change

<body>
    <ul class="baidu">
        <li><img src="images/1.jpg"></li>
        <li><img src="images/2.jpg"></li>
        <li><img src="images/3.jpg"></li>
        <li><img src="images/4.jpg"></li>
    </ul>
    <script>
        // 1. Get element
        var imgs = document.querySelector('.baidu').querySelectorAll('img');
        // console.log(imgs);
        // 2. Circular registration event
        for (var i = 0; i < imgs.length; i++) {
            imgs[i].onclick = function() {
                // this.src , is the path where we click on the image , images / 2 jpg
                // console.log(this.src);
                //Put this path {this SRC , just give it to body ,
                document.body.style.backgroundImage = 'url(' + this.src + ')';
            }
        }
    </script>
</body>

Case: table interlaced color change

    <script>
        // 1. Get element , gets all the lines in , tbody ,
        var trs = document.querySelector('tbody').querySelectorAll('tr');
        // 2. Register events with circular binding
        for (var i = 0; i < trs.length; i++) {
            // 3. Mouse over event onmouseover
            trs[i].onmouseover = function({
                    // console.log(11);
                    this.className = 'bg';
                }
                // 4. The mouse leaves the event onmouseout
            trs[i].onmouseout = function({
                this.className = '';
            }
        }
    </script>

Case: select all

    <script>
        // 1. Select all and deselect all: let the checked attribute (selected status) of all the check boxes below follow the select all button
        //Get 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: the selected 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 child checkboxes
        for (var i = 0; i < j_tbs.length; i++) {
            j_tbs[i].onclick = function({
                //flag # controls whether the select all button is selected
                var flag = true;
                //Each time you click the check box below, you will cycle 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
                    }
                }
                //Sets the status of the select all button
                j_cbAll.checked = flag;
            }
        }
    </script>

Custom attribute action

1. Get attribute value

    <div id="demo" index="1" class="nav"></div>
    <script>
        var div = document.querySelector('div');
        /
/ 1. Gets the attribute value of the element
        /
/ (1) element.attribute
        console.log(div.id);
        /
/(2) element.getAttribute('attribute')  get Get get attribute Meaning of attribute The properties added by our programmers are called custom properties index
        console.log(div.getAttribute('id'));
        console.log(div.getAttribute('index'));
 </
script>

2. Set attribute value

        // 2. Set element attribute value
        // (1) element. Attribute = 'value'
        div.id = 'test';
        div.className = 'navs';
        // (2) element.setAttribute('attribute ',' value '); Mainly for custom attributes
        div.setAttribute('index'2);
        div.setAttribute('class''footer'); //class , what's written here is

3. Remove attribute

  //class is not className
        //3. Remove attribute} removeattribute (attribute)
        div.removeAttribute('index');

4. Case: tab column

    <script>
        //Get element
        var tab_list = document.querySelector('.tab_list');
        var lis = tab_list.querySelectorAll('li');
        var items = document.querySelectorAll('.item');
        //for loop to bind click events to tabs
        for (var i = 0; i < lis.length; i++) {
            //Start setting index numbers for the five small li#
            lis[i].setAttribute('index', i);
            lis[i].onclick = function({
                // 1. On the module tab, the current background color will be red, and the rest will remain unchanged (exclusive thought)
                //Kill everyone and the rest of the class
                for (var i = 0; i < lis.length; i++) {
                    lis[i].className = '';
                }
                //Leave me alone
                this.className = 'current';
                // 2. The following display content module
                var index = this.getAttribute('index');
                console.log(index);
                //Kill everyone and hide the rest of the item s
                for (var i = 0; i < items.length; i++) {
                    items[i].style.display = 'none';
                }
                //Leave me , so that the corresponding item , is displayed
                items[index].style.display = 'block';
            }
        }
    </script>

5. H5 custom attribute

Custom attribute purpose: to save and use data. Some data can be saved to the page instead of the database.

The custom attribute is obtained through getAttribute('attribute ').

However, some custom attributes are easy to cause ambiguity, and it is not easy to judge whether they are built-in attributes or custom attributes of elements.

H5 adds custom attributes to us:

    <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 New method to get custom attributes It can only get data-initial
        /
/ dataset It's a collection that holds all the information data Custom attributes at the beginning
        console.log(div.dataset);
        console.log(div.dataset.index);
        console.log(div.dataset['index']);
        /
/ If there are multiple custom attributes-Link the words we take when we get them Hump nomenclature
        console.log(div.dataset.listName);
        console.log(div.dataset['listName']);
    </
script>

Node operation

1. Node overview

​ All contents in a web page are nodes (labels, attributes, text, comments, etc.), and nodes are represented by nodes in DOM.

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

​ Generally, a node has at least three basic attributes: nodeType, nodeName, and nodeValue.

2. Node level

​ Using DOM tree, nodes can be divided into different hierarchical relationships, commonly parent-child brother hierarchical relationships.

3. Parent node

    <div class="demo">
        <div class="box">
            <span class="erweima">×</span>
        </div>

    </div>
    <script>
        /
/ 1. Parent node parentNode
        var erweima = document.querySelector('.erweima');
        /
/ var box = document.querySelector('.box');
        /
/ The result is the nearest parent node to the element(Pro Dad) If the parent node cannot be found, it returns as null
        console.log(erweima.parentNode);
    </
script>

4. Child nodes

Child element node

    <ul>
        <li>I am li</li>
        <li>I am li</li>
        <li>I am li</li>
        <li>I am li</li>
    </ul>
    <script>
        /
/ DOM Methods provided( API)obtain
        var ul = document.querySelector('ul');
        var lis = ul.querySelectorAll('li');
        /
/ 1. Child node  childNodes All child nodes contain Element node Text nodes, etc
        console.log(ul.childNodes);
        console.log(ul.childNodes[0].nodeType);
        console.log(ul.childNodes[1].nodeType);
        /
/ 2. children Get all child element nodes It is also commonly used in our actual development
        console.log(ul.children);
    </
script>

​ In the actual development, firstChild and lastChild contain other nodes, which is inconvenient to operate, and firstElementChild and lastElementChild have compatibility problems, so how do we get the first child element node or the last child element node?

    <ol>
        <li>I am li1</li>
        <li>I am li2</li>
        <li>I am li3</li>
        <li>I am li4</li>
        <li>I am li5</li>
    </ol>
    <script>
        var ol = document.querySelector('ol');
        /
/ 1. firstChild First child node Whether it's a text node or an element node
        console.log(ol.firstChild);
        console.log(ol.lastChild);
        /
/ 2. firstElementChild Returns the first child element node ie9 Only support
        console.log(ol.firstElementChild);
        console.log(ol.lastElementChild);
        /
/ 3. Writing method of actual development  Returns the first child element without compatibility issues
        console.log(ol.children[0]);
        console.log(ol.children[ol.children.length - 1]);
    </
script>

5. Case: Sina drop-down menu

    <script>
        // 1. Get element
        var nav = document.querySelector('.nav');
        var lis = nav.children; //Get 4 small li
        // 2. Circular registration event
        for (var i = 0; i < lis.length; i++) {
            lis[i].onmouseover = function({
                this.children[1].style.display = 'block';
            }
            lis[i].onmouseout = function({
                this.children[1].style.display = 'none';
            }
        }
    </script>

6. Brother node

    <div>I am div</div>
    <span>I am span</
span>
    <script>
        var div = document.querySelector('div');
        // 1.nextSibling , the next sibling node , contains element nodes or , text nodes, and so on
        console.log(div.nextSibling);
        console.log(div.previousSibling);
        // 2. Nextlementsibling , get the next sibling element node
        console.log(div.nextElementSibling);
        console.log(div.previousElementSibling);
    
</script>


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

7. Add node

    <ul>
        <li>123</li>
    </ul>
    <script>
        /
/ 1. Create node element node
        var li = document.createElement('li');
        /
/ 2. Add node node.appendChild(child)  node Parent  child Is a child Append element after
        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. Create element 2. Add element
    </
script>

8. Case: simple version release message

<body>
    <textarea name="" id=""></textarea>
    <button>release</button>
    <ul>

    </ul>

    <script>
        // 1. Get element
        var btn = document.querySelector('button');
        var text = document.querySelector('textarea');
        var ul = document.querySelector('ul');
        // 2. Registration event
        btn.onclick = function({
            if (text.value == '') {
                alert('You have not entered anything');
                return false;
            } else {
                // console.log(text.value);
                //(1) create element
                var li = document.createElement('li');
                //li , must be present before assignment
                li.innerHTML = text.value;
                //(2) add elements
                // ul.appendChild(li);
                ul.insertBefore(li, ul.children[0]);
            }
        }
    
</script>

</body>

9. Delete node

node. The removechild () method deletes a child node from the node node and returns the deleted node.

    <button>delete</button>
    <ul>
        <li>Xiong Da</
li>
        <li>Xiong er</li>
        <li>Bald head strength</li>
    </ul>
    <script>
        /
/ 1.Get element
        var ul = document.querySelector('ul');
        var btn = document.querySelector('button');
        /
/ 2. Delete 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>

10. Case: delete message

    <textarea name="" id=""></textarea>
    <button>release</
button>
    <ul>

    </ul>

    <script>
        // 1. Get element
        var btn = document.querySelector('button');
        var text = document.querySelector('textarea');
        var ul = document.querySelector('ul');
        // 2. Registration event
        btn.onclick = function({
            if (text.value == '') {
                alert('You have not entered anything');
                return false;
            } else {
                // console.log(text.value);
                //(1) create element
                var li = document.createElement('li');
                //li , must be present before assignment
                li.innerHTML = text.value + "<a href='javascript:;'>delete</a>";
                //(2) add elements
                // ul.appendChild(li);
                ul.insertBefore(li, ul.children[0]);
                //(3) delete the element ^ delete the li of the current link ^ its father
                var as = document.querySelectorAll('a');
                for (var i = 0; i < as.length; i++) {
                    as[i].onclick = function({
                        //Delete the li # this where the current a is located parentNode;
                        ul.removeChild(this.parentNode);
                    }
                }
            }
        }
    
</script>

11. Copy (clone) nodes

    <ul>
        <li>1111</li>
        <li>2</li>
        <li>3</li>
    </ul>
    <script>
        var ul = document.querySelector('ul');
        /
/ 1. node.cloneNode(); Parentheses are empty or inside false Shallow copy Only copy the label, not the content
        /
/ 2. node.cloneNode(true); Parentheses are true Deep copy Copy the label and copy the contents
        var lili = ul.children[0].cloneNode(true);
        ul.appendChild(lili);
    </
script>

12. Case: dynamically generate tables

    <script>
        // 1. First prepare the student's data
        var datas = [{
            name'Wei Yingluo',
            subject'JavaScript',
            score100
        }, {
            name'Hongli',
            subject'JavaScript',
            score98
        }, {
            name'Fu Heng',
            subject'JavaScript',
            score99
        }, {
            name'Mingyu',
            subject'JavaScript',
            score88
        }, {
            name'unfaithful man',
            subject'JavaScript',
            score0
        }];
        // 2. Create rows into tbody #: we will create a few rows for a few people (through the length of the array)
        var tbody = document.querySelector('tbody');
  //Traversal array
        for (var i = 0; i < datas.length; i++) { 
            // 1. Create tr row
            var tr = document.createElement('tr');
            tbody.appendChild(tr);
            // 2. The number of cells created in the row depends on the number of attributes in each object
            //Use for # in to traverse the student object
            for (var k in datas[i]) { 
                //Create cell
                var td = document.createElement('td');
                //Give the attribute value {data [i] [k] in the object to} td
                td.innerHTML = datas[i][k];
                tr.appendChild(td);
            }
            // 3. Create a cell with 2 words deleted
            var td = document.createElement('td');
            td.innerHTML = '<a href="javascript:;">delete </a>';
            tr.appendChild(td);

        }
        // 4. Delete operation} started
        var as = document.querySelectorAll('a');
        for (var i = 0; i < as.length; i++) {
            as[i].onclick = function({
                //Click a , delete the current line (linked dad's dad) node removeChild(child)  
                tbody.removeChild(this.parentNode.parentNode)
            }
        }
    </script>

Three ways to create elements

    <script>
        //Differences between the three methods of creating elements
        // 1.  document.write() creates an element. If the page document stream is loaded, calling this sentence again will cause the page to be redrawn
         var btn = document.querySelector('button');
         btn.onclick = function({
             document.write('<div>123</div>');
         }

        // 2. innerHTML create element
        var inner = document.querySelector('.inner');
         for (var i = 0; i <= 100; i++) {
             inner.innerHTML += '<a href="#">Baidu</a>'
         }
        var arr = [];
        for (var i = 0; i <= 100; i++) {
            arr.push('<a href="#"> Baidu < / a > ');
        }
        inner.innerHTML = arr.join('');
        // 3.  document.createElement() creates an element
        var create = document.querySelector('.create');
        for (var i = 0; i <= 100; i++) {
            var a = document.createElement('a');
            create.appendChild(a);
        }
    </script>

13. Comparison of innerthml and createElement efficiency

innerHTML string splicing method (low efficiency)

<script>
    function fn({
        var d1 = +new Date();
        var str = '';
        for (var i = 0; i < 1000; i++) {
            document.body.innerHTML += '<div style="width:100px; height:2px; border:1px solid blue;"></div>';
        }
        var d2 = +new Date();
        console.log(d2 - d1);
    }
    fn();
</script>

createElement mode (average efficiency)

<script>
    function fn({
        var d1 = +new Date();

        for (var i = 0; i < 1000; i++) {
            var div = document.createElement('div');
            div.style.width = '100px';
            div.style.height = '2px';
            div.style.border = '1px solid red';
            document.body.appendChild(div);
        }
        var d2 = +new Date();
        console.log(d2 - d1);
    }
    fn();
</script>

innerHTML array mode (high efficiency)

<script>
    function fn({
        var d1 = +new Date();
        var array = [];
        for (var i = 0; i < 1000; i++) {
            array.push('<div style="width:100px; height:2px; border:1px solid blue;"></div>');
        }
        document.body.innerHTML = array.join('');
        var d2 = +new Date();
        console.log(d2 - d1);
    }
    fn();
</script>

The core summary of DOM

With regard to dom operations, we mainly focus on element operations. It mainly includes creation, addition, deletion, modification, query, attribute operation and event operation.

- END -