APl DOM Document Object Model

1. Introduction to DOM

1. What is DOM

  • The Document Object Model (DOM for short) is a standard programming interface recommended by the W3C organization for processing extensible markup languages. W3C has defined a series of DOM interfaces through which the content and structural style of web pages can be changed.

2. DOM tree

Insert picture description here

  • Document: A page is a document, which is represented by document in the DOM
  • Element: All tags in the page are elements, which are represented by element in the DOM
  • Node: All content in the web page is a node (labels, attributes, text, comments, etc.). The use of node in the DOM represents the
    DOM. The above content is regarded as an object

2. Methods of getting elements

1. There are several ways to get the elements in the page

  • Get by ID
  • Get according to tag name
  • Obtained by the new method of HTML5
  • Special element acquisition

1. Obtain by ID

  • Use the getElementByld() method to get the element object with ID

Code demo

<body>
    <div id="time">2020-11-26</div>
    <script>
        // 1.因为我们文档页面从上往下加载,所以先得有标签 所以我们的script写在标签下面
        // 2.    document文档    get 获得 element 元素 by 通过 驼峰命名法
        // 3.参数 id是大小写敏感的字符串
        // 4.返回的是一个对象
        var timer = document.getElementById('time');
        console.log(timer);
        // 5.console.dir 打印我们返回得的元素对象 更好的查看里面的属性和方法
        console.dir(timer);
    </script>
</body>

2. Obtain according to the tag name

  • Use the getElementsByTagName() method to return a collection of objects with the specified tag name. The
    syntax is as follows
document.getElementsByTagName('标签名')

note:

  • 1. Because what we get is a collection of objects, we need to traverse to use the elements we want to manipulate
  • Get the element object to be dynamic

Code demo

<body>
    <ul>
        <li>我们的征程是星辰大海</li>
        <li>我们的征程是星辰大海</li>
        <li>我们的征程是星辰大海</li>
        <li>我们的征程是星辰大海</li>
        <li>我们的征程是星辰大海</li>
    </ul>
    <ul id="nav">
        <li>心存感恩,所遇皆美好~</li>
        <li>心存感恩,所遇皆美好~</li>
        <li>心存感恩,所遇皆美好~</li>
        <li>心存感恩,所遇皆美好~</li>
        <li>心存感恩,所遇皆美好~</li>
    </ul>
    <script>
        // 1.返回的是 获取过来元素对象的集合 以伪数组的形式存储的
        var lis = document.getElementsByTagName('li')
        console.log(lis);
        // 2.如果想要依次打印里面的元素对象我们可以采取遍历方式
        for (var i = 0; i < lis.length; i++) {
            console.log(lis[i]);
        }
        // 3.这里可以是可以获取标签的.getElementsByTagName()可以得到这个元素里面的某些标签
        var nav1 = document.getElementById('nav') //这个获取nav元素
        var navli = nav.getElementsByTagName('li') //这里是获取nav 里面的li标签  要先获取 nav元素在获取里面的li
        console.log(navli);
    </script>
</body>

3. Obtain through the new method of HTML5 (note compatibility)

1. document.getElementsByClassName(‘类名’);// 根据类名返回元素对象集合
2. document.querySelector('选择器'); // 根据指定选择器返回第一个元素对象
3. document.querySelectorAll('选择器'); // 根据指定选择器返回

Note: The selectors in querySelector and querySelectorAll need to add symbols , such as: document.querySelector('#nav');

Code demo

<body>
    <div class="box">盒子1</div>
    <div class="box">盒子2</div>
    <div id="nav">
        <ul>
            <li>首页</li>
            <li>产品</li>
        </ul>
    </div>
    <script>
        // 1. getElementsByClassName 根据类名获得某些元素集合
        var boxs = document.getElementsByClassName('box');
        console.log(boxs);
        // 2. querySelector 返回指定选择器的第一个元素对象  切记 里面的选择器需要加符号 .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()返回指定选择器的所有元素对象集合
        var allBox = document.querySelectorAll('.box');
        console.log(allBox);
        var lis = document.querySelectorAll('li');
        console.log(lis);
    </script>

4. Get special elements (body, html)

  • Get the body element
 - doucumnet.body // 返回body元素对象
  • Get html element
. document.documentElement // 返回html元素对象

Code demo

<body>
    <script>
        // 获取bdoy元素
        var bodyEle = document.body
        console.log(bodyEle); //返回body元素
        // 获取html元素
        var htmlEle = document.documentElement
        console.log(htmlEle); //返回html元素
    </script>
</body>

3. 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.
  • Every element in a web page can generate certain events that can trigger JavaScript. For example, we can generate an
    event when the user clicks a button , and then perform certain operations.

Code demo

<body>
    <button id="btn">浩哥</button>
    <script>
        // 点击一个按钮,弹出一个对话框
        // 1.事件是有三部分组成的 1.事件源 2.事件类型 3.事件处理程序 也称为事件三要素
        // (1).事件源 事件被触发的对象  
        var but = document.getElementById('btn')
            // (2).事件类型   如何触发 什么事件 比如鼠标点击(onclick) 还是鼠标经过还是????
            // (3).事件处理程序 通过一个函数赋值的方式 完成  因为函数就是实现某种功能的
        but.onclick = function() {
            alert('浩哥爱编程')
        }
    </script>
</body>

Insert picture description here

2. Steps to execute the event

1. Get the event source (meaning that you want to get the element)
2. Register the event (binding the event means how to handle the behavior, such as mouse passing or mouse click, etc.)
3. Add event handler (using function assignment Form means what you want to do)

Code demo

<body>
    <div>123</div>
    <script>
        // 事件执行步骤   点击div 控制台输出我被选中了
        // 1.获取事件源
        var div = document.querySelector('div')
            // 2.绑定事件 注册事件
            // div.onclick
            // 3.添加事件处理程序
        div.onclick = function() {
            console.log('我被点击了');
        }
    </script>
</body>

Insert picture description here

3. Common mouse events

Insert picture description here
The mouse is constantly moving, use the mouse movement event: mousemove

Four. Operating elements

JS's DOM operation can change the content, structure and style of web pages, and use DOM operation elements to change the content and attributes of the elements. Note that the following are all attributes

1. Operation element content (change element content)

elemeny.innerText

The content from the start position to the end position, but it removes html tags, and spaces and line breaks are also removed

elemernt.innerHTML

All content from the start position to the end position, including html tags, while preserving spaces and line breaks

Code demo

  <title>Document</title>
    <style>
        div,
        p {
            height: 30px;
            width: 300px;
            line-height: 30px;
            text-align: center;
            color: #fff;
            background-color: pink;
        }
    </style>
</head>

<body>
    <button>显示当前系统时间</button>
    <div>某个时间</div>
    <p>123</p>
    <script>
        // 当我们点击了按钮,div里面的文字会发生变化
        // 1.获取元素  注意这里的按钮 和div都要获取到 因为 点击按钮div里面要发生变化所以都要获取
        var but = document.querySelector('button');
        var div = document.querySelector('div');
        // 2.绑定事件
        // but.onclick
        // 3.程序处理
        but.onclick = function() {
        // 改变元素内容 element(元素).innerText
        div.innerText = '2020-11-27'
        }
        // 4.我们元素可以不用添加事件,就可以直接显示日期
        var p = document.querySelector('p');
        p.innerText = '2020-11-27';
    </script>

Insert picture description here

The difference between elemeny.innerText and elemeny.innerHTML
Code demo

<body>
    <div></div>
    <p></p>
    <ul>
        <li> 文字</li>
        <li>123</li>
    </ul>
    <script>
        // innertText 和 innertHTML 的区别
        // 1. innerText 不识别html标签 非标准 去除空格和换行
        var div = document.querySelector('div');
        div.innerText = '<strong>今天是:</strong> 2020';

        // 2.innertHTML 识别html标签 W3C标准 保留空格和换行的   推荐尽量使用这个 因为这个是标准
        var p = document.querySelector('p')
        p.innerHTML = '<strong>今天是:</strong> 2020';

        // 3.这俩个属性是可读写的 意思是 除了改变内容还可以获得元素里面的内容的
        var ul = document.querySelector('ul')
        console.log(ul.innerText);
        console.log(ul.innerHTML);
    </script>
</body>

Insert picture description here

2. Manipulate common element attributes

  1. innerText, innerHTML change element content
  2. src、href
  3. id、alt、title

Code demo

<body>
    <button id="ldh">刘德华</button>
    <button id="zxy">张学友</button><br>
    <img src="./images/ldh.jpg" alt="" width="200px" height="200px" title="刘德华" id="img">
    <script>
        // 修改属性 src
        // 我们可以操作元素得方法 来修改元素得属性 就是 元素的是什么属性 在重新给值就可以完成相应的赋值操作了
        // 1.获取元素
        var ldh = document.getElementById('ldh')
        var zxy = document.getElementById('zxy')
        var img = document.getElementById('img')
            // 2.注册事件 程序处理
        zxy.onclick = function() {
            // 当我们点击了图片的时候图片路径就发生变化   这里的.表示 的 得意思
            img.src = './images/zxy.jpg';
            // 当我们变换图片得同时里面得title也要跟着变 所以前面要加上img.
            img.title = '张学友';
        }
        ldh.onclick = function() {
            img.src = './images/ldh.jpg';
            img.title = '刘德华';
        }
    </script>

Insert picture description here

3. Manipulate form element attributes

Use the DOM to manipulate the attributes of the following form elements

type、value、checked、selected、disabled

Code demo:

<body>
    <button>按钮</button>
    <input type="text" value="输入内容">
    <script>
        // 我想把value里面的输入内容改变为 被点击了
        // 1.获取元素
        var but = document.querySelector('button')
        var input = document.querySelector('input')
            // 2.注册事件 处理程序
        but.onclick = function() {
            // input.innerHTML = '被点击了'; 这个是 普通盒子 比如 div 标签里面的内容
            // 表单里面的值 文字内容是通过value来修改的
            input.value = '被点击了'
                // 如果需要某个表单被禁用 不能再点击了使用 disabled  我们想要这个按钮 button禁用
                // but.disabled = true
                // 还有一种写法
                // this指向的是事件函数的调用者 谁调用就指向谁 这里调用者是btn
            this.disabled = true
        }
    </script>
</body>

Insert picture description here

4. Manipulate element style attributes

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

 1.element.style 行内样式操作

note:

  • The styles in JS adopt camel case nomenclature such as fontSize, backgroundColor
  • JS modifies the style operation to produce inline styles, so the inline style is higher than the inline style

Code demo

   <style>
        div {
            width: 200px;
            height: 200px;
            background-color: red;
        }
    </style>
</head>

<body>
    <div></div>
    <script>
        // 要求点击div变成粉色 height变为250px
        // 1.获取元素
        var div = document.querySelector('div');
        // 2.注册事件 处理程序
        div.onclick = function() {
            // div.style里面的属性 采取的是驼峰命名法
            // this等于div this调用者 谁调用谁执行
            this.style.backgroundColor = 'pink'
            this.style.height = '250px'
        }
    </script>

Insert picture description here

 2.element.className 类名样式操作

note:

  • If there are many style changes, you can change the element style by operating the class name.
  • Because class is a reserved word, use className to manipulate element class name attributes
  • className will directly change the class name of the element and will overwrite the original class name.

Code demo

  <style>
        div {
            width: 100px;
            height: 100px;
            background-color: pink;
        }
        
        .change {
            background-color: purple;
            color: #fff;
            font-size: 25px;
            margin-top: 100px;
        }
    </style>
</head>


<body>
    <div class="first">文本</div>
    <script>
        // 1. 使用 element.style 获得修改元素样式  如果样式比较少 或者 功能简单的情况下使用
        var test = document.querySelector('div');
        test.onclick = function() {
            // this.style.backgroundColor = 'purple';
            // this.style.color = '#fff';
            // this.style.fontSize = '25px';
            // this.style.marginTop = '100px';
            // 让我们当前元素的类名改为了 change

            // 2. 我们可以通过 修改元素的className更改元素的样式 适合于样式较多或者功能复杂的情况 如果想继续添加样式即在change添加即可
            // 3. 如果想要保留原先的类名,我们可以这么做 多类名选择器
            // this.className = 'change';
            this.className = 'first change';
        }
    </script>

Insert picture description here

5. Operation of custom attributes

1. Get the attribute value

  • The element. attribute gets the attribute value.
  • element.getAttribute('Attribute');

the difference:

  • element.attribute to get the value of the built-in attribute (the attribute that comes with the element itself)
  • element.getAttribute('attribute'); Mainly get custom attributes (standard) our custom attributes

2. Set the attribute value

  • element.attribute ='value' set the value of the built-in attribute
  • element.setAttribute('attribute','value')

the difference:

  • element. property sets the built-in property value
  • element.setAttribute('attribute'); Mainly set custom attributes (standard)

3. Remove attributes

  • element.removeAttribute('attribute');

Code demo

<body>
    <div id="demo" index="1" class="nav"></div>
    <script>
        var div = document.querySelector('div');
        // 1.获取元素的属性值
        // (1) element.属性
        console.log(div.id);
        // (2) element.getAttribute('属性') get获取得到 attribute属性的意思 我们自己添加的属性称之为自定义属性
        console.log(div.getAttribute('id')); //demo
        console.log(div.getAttribute('index')); // 1
        // 2.修改元素的属性值
        // (1) element.属性 = '值' 
        div.id = 'test'
        div.className = 'navs'
            // (2) element.setAttribute('属性','值')
        div.setAttribute('index', 2);
        div.setAttribute('class', 'footer') //这里就是class 不是className 比较特殊
            // 3.移除属性 removeAttribute(属性)
        div.removeAttribute('index');
    </script>
</body>

  • As long as it is a custom attribute, it is best to use element.setAttribute('attribute','value') to set. If it is a self-contained attribute, use element.attribute to set

6.H5 custom attributes

The purpose of custom attributes: first, to save attributes , and second, to use data . Some data can be saved to the page without saving to the database.
Custom attributes are obtained through getAttribute('attribute'),
but some custom attributes are easy to cause ambiguity, and it is not easy to determine whether it is an element or a custom attribute.
H5 adds custom attributes to us :
1. Set H5 custom attributes

  • H5 stipulates that the custom attribute data- begins as the attribute name and assigns a value such as <div data-index: "1">
  • Or use JS to set element.setAttribute('deta-index', 2)

2. Get H5 custom attributes

  • Compatibility Get element.getAttribute ( 'data-index') pushes recommended to use this development
  • H5 added element.dataset.index or element.datase['index'] ie 11 or above is only supported

Code demo

<body>
    <div getTime="10" data-index="20" data-name-list="40"></div>
    <script>
        // 获取元素
        var div = document.querySelector('div');

        console.log(div.geTime); //undefined  getTime是自定义属性不能直接通过元素的属性来获取 而是用自定义属性来获取的getAttribute(‘属性’)

        console.log(div.getAttribute('getTime')); //10
        // H5添加自定义属性的写法以data-开头
        div.setAttribute('data-time', 30)
            // 1.兼容性获取H5自定义属性
        console.log(div.getAttribute('data-time')); // 30
        // 2.H5新增的获取自定义属性的方法  它只能获取data-开头的
        // dataset 是一个集合的意思存放了所有以data开头的自定义属性  如果你想取其中的某一个只需要在dataset.的后面加上自定义属性名即可
        console.log(div.dataset);
        console.log(div.dataset.time); // 30
        // 还有一种方法dataset['属性']
        console.log(div.dataset['time']); // 30
        // 如果自定义属性里面有多个-链接的单词 我们获取的时候采取驼峰命名法 不用要-了
        console.log(div.dataset.nameList); // 40
        console.log(div.dataset['nameList']); // 40
    </script>
</body>


Five. Node operation

1. Why learn node operation

There are usually two ways to obtain elements
(1) Use the methods provided by DOM to obtain elements but the logic is not strong and cumbersome
(2) Use node hierarchical relationships to obtain elements, such as parent-child, sibling relationships, have strong logic, but the compatibility is not very good

2. Node overview

All content in a web page are nodes (labels, attributes, text, comments, etc.). In the DOM, nodes are represented by nodes.
All nodes in the HTML DOM tree can be accessed through javascript, all HTML elements (nodes) can be modified, and can also be created or deleted.
Insert picture description hereGenerally, nodes have at least nade Type (node ​​type), nodeName (node ​​name) and nodeValue (Node value) These three basic attributes

  • Element node nodeType is 1
  • The nodeType of the attribute node is 2
  • The nodeType of the text node is 3 (the text node contains text, spaces, line breaks, etc.)

In actual development, node operations mainly operate element nodes

3. Node level

The DOM tree can be used to divide the nodes into different hierarchical relationships, which are usually the father-son-brother hierarchical relationship

1. Parent node

1.node.parentNode
  • The parenNode attribute can return the parent node of a node, pay attention to the nearest parent node! ! !
  • If the specified node has no parent node, it returns null

Code demo

<body>
    <div class="box">
        <div class="box1"></div>
    </div>
    <script>
        var box1 = document.querySelector('.box1')
            // 得到的是离元素最近的父节点(亲爸爸) 得不到就返回得是null
        console.log(box1.parentNode); // parentNode 翻译过来就是父亲的节点
    </script>
</body>

2. Child node operation

1.parentNode.children(非标准)

parentNode.children is a read-only property that returns all child element nodes . It only returns the child element nodes, and the rest of the nodes do not return (mainly remember this, I will use
it later ) Although children is a non-standard, but it is supported by various browsers, we can use it boldly! ! !

Code demo

<body>
    <ul>
        <li>1</li>
        <li>1</li>
        <li>1</li>
        <li>1</li>
    </ul>
    <script>
        //   DOM 提供的方法(APL)获取 这样获取比较麻烦
        var ul = document.querySelector('ul')
        var lis = ul.querySelectorAll('li')
         // children子节点获取  ul里面所有的小li 放心使用没有限制兼容性 实际开发中经常使用的
        console.log(ul.children);
    </script>

How to return the first and last child nodes?

2.parentNode.firstElementChild

firstElementChild returns the first child element node , if not found, it returns unll

3.parentNode.lastElementChild

lastElementChild returns the last child element node , or null if not found

Note: These two methods have compatibility issues. Only IE9 and above can be used with caution,
but we have a solution.

如果想要第一个子元素节点,可以使用 parentNode.chilren[0] 
如果想要最后一个子元素节点,可以使用 parentNode.chilren[parentNode.chilren.length - 1] 

Code demo

<body>
    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
    </ul>
    <script>
        var ul = document.querySelector('ul')
            // 1.firstElementChild 返回第一个子元素节点 ie9 以上才支持注意兼容
        console.log(ul.firstElementChild);
        // 2.lastElementChild返回最后一个子元素节点
        console.log(ul.lastElementChild);
        // 3.实际开发中用到的既没有兼容性问题又可以返回子节点的第一个和最后一个
        console.log(ul.children[0]);
        console.log(ul.children[ul.children.length - 1]); //ul.children.length - 1获取的永远是子节点最后一个
    </script>
</body>

3. Siblings

1.node.nextSibling

nextSibling returns the next sibling node of the current element , or null if it is not found. Note that all nodes are included

2.node.previousSibling 

previousSibling returns the previous sibling node of the current element , or null if it is not found. Note that all nodes are included

Code demo

<body>
    <div>我是div</div>
    <span>我是span</span>
    <script>
        var div = document.querySelector('div')
            // 返回当前元素的下一个兄弟节点nextSibling,找不到返回null。注意包含元素节点或者文本节点等等
        console.log(div.nextSibling); //这里返回的是#text 因为它的下一个兄弟节点是换行
        // 返回的是当前元素的上一个节点previousSibling,找不到返回null。注意包含元素节点或者文本节点等等
        console.log(div.previousSibling); //这里返回的是#text 因为它的上一个兄弟节点是换行
    </script>
</body>

3.node.nexElementSibling

nexElementSibling returns the next sibling element node of the current element, returns null if not found

4.node.previousElementSibling

previousElementSibling returns the previous sibling node of the current element, returns null if not found

Note: These two methods have compatibility issues and are only supported by IE9 and above

Code demo

<body>
    <div>我是div</div>
    <span>我是span</span>
    <script>
        var div = document.querySelector('div')
        // nextElementSiblingd得到下一个兄弟元素节点
        console.log(div.nextElementSibling); // span  
        // previousElementSibling  得到的是上一个兄弟元素节点
        console.log(div.previousElementSibling); // null 因为它上面没有兄弟元素了返回空的
    </script>
</body>

How to solve the compatibility problem?
Can encapsulate a compatibility function (a simple understanding can be used in actual development)

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

4. Create Node

1.document.createElement('tagName')

The document.createElement() method creates the HTML element specified by tagName. Because these elements that did not exist before are dynamically generated according to our needs, so we are also called dynamically creating element nodes

We have created a node to be added to the node to be called adding a node

1.node.appendChild(child)

The node.appendChild() method adds a node to the end of the child node list of the specified parent node

2.node.insertBefore(child,指定元素)

The node.insertBefore() method adds a node in front of the specified child node of the parent node

Code demo

<body>
    <ul>
        <li>1</li>
    </ul>
    <script>
        // 1.创建节点 createElement
        var li = document.createElement('li')
            // 2.添加节点 创建了节点要添加到某一个元素身上去 叫添加节点 node.appendChild(child) done 父级 child 子级 如果前面有元素了则在后面追加元素类似数组中的push依次追加
        var ul = document.querySelector('ul')
        ul.appendChild(li)
            // 3.添加节点 node.insertBefore(child,指定元素) 在子节点前面添加子节点 child子级你要添加的元素
        var lili = document.createElement('li')
        ul.insertBefore(lili, ul.children[0]) //ul.children 这句话的意思是添加到ul父亲的子节点第一个
            // 总结 如果想在页面中添加元素分为俩步骤1.创建元素 2.添加元素
    </script>
</body>

Insert picture description here
5. Delete the node

node.removeChild(child)

The node.removeChlid() method deletes a child node from the DOM, and returns the deleted node. The simple point is to delete a child from the parent element. The node is the father and the child is the child.

Code demo

<body>
    <button>按钮</button>
    <ul>
        <li>熊大</li>
        <li>熊二</li>
        <li>熊三</li>
    </ul>
    <script>
        // 1.获取元素
        var ul = document.querySelector('ul')
        var but = document.querySelector('button');
        // 2.删除元素
        // but.onclick = function() {
        //     ul.removeChild(ul.children[0])
        // }
        // 3.点击按钮键依次删除,最后没有删除内容了 就禁用按钮 disabled = true 禁用按钮语法
        but.onclick = function() {
            if (ul.children.length == 0) {
                this.disabled = true
            } else {
                ul.removeChild(ul.children[0])
            }
        }
    </script>
</body>

Insert picture description here
6. Duplicate node (clone node)

node.cloneNode()

The node.dloneNode() method returns a copy of the node that called the method, also known as a clone node/copy node

Note
1. If the parenthesis parameter is empty or false, it is a shallow copy, only the label inside is copied, and the content is not copied
2. If the parenthesis parameter is true, it is a deep copy, which will copy the node itself and all the contents inside

Code demo

<body>
    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
    </ul>
    <script>
        // 1.获取元素
        var ul = document.querySelector('ul');
        // 2.复制元素 node.cloneNode()   如果参数括号为空或者false则只会复制元素不会复制内容,如果待有参数true则内容和元素都会被复制
        var lis = ul.children[0].cloneNode(true);
        // 3.获取元素
        ul.appendChild(lis)
    </script>
</body>


Insert picture description here
7. The difference between the three dynamically created elements

  • document.write()
  • element.innerHTML
  • document.createElement()

the difference

  1. document.write() is a content stream that directly writes content to the page, but after the document stream is executed, it will cause the page to be redrawn.
  2. element.innerHTML is to write the content to a DOM node, which will not cause the page to be redrawn
  3. element.innerHTML is more efficient to create multiple elements (don't splice strings, use array splicing), the result is a bit complicated
  4. createElement() is a little less efficient to create multiple elements, but the result is clearer

Summary: In different browsers, innerHTML is more efficient than createElement()

Code demo

<body>
    <button>点击</button>
    <p>abc</p>
    <div class="inner"></div>
    <div class="create"></div>
    <script>
        // window.onload = function() {
        //         document.write('<div>123</div>');

        //     }
        // 三种创建元素方式区别 
        // 1. document.write() 创建元素  如果页面文档流加载完毕,再调用这句话会导致页面重绘
        // var btn = document.querySelector('button');
        // btn.onclick = function() {
        //     document.write('<div>123</div>');
        // }

        // 2. innerHTML 创建元素
        var inner = document.querySelector('.inner');
        // for (var i = 0; i <= 100; i++) {
        //     inner.innerHTML += '<a href="#">百度</a>'
        // }
        var arr = [];
        for (var i = 0; i <= 100; i++) {
            arr.push('<a href="#">百度</a>');
        }
        inner.innerHTML = arr.join('');
        // 3. document.createElement() 创建元素
        var create = document.querySelector('.create');
        for (var i = 0; i <= 100; i++) {
            var a = document.createElement('a');
            create.appendChild(a);
        }
    </script>
</body>

Guess you like

Origin blog.csdn.net/m0_46978034/article/details/110190352