4. Manipulate elements

Example: An error message is displayed in the password box

If the entered number is not 6 to 16, an error message is displayed. If the entered number is not 6 to 16, the correct message is displayed

The password is displayed before the user enters the password. Enter a password of 6 to 16 characters.

<style>
        div {
            width: 600px;
            margin: 100px auto;
        }
        
        .message {
            display: inline-block;
            font-size: 12px;
            color: #999;
            background: url(images/mess.png) no-repeat left center;
            padding-left: 20px;
        }
        
        .wrong {
            color: red;
            background-image: url(images/wrong.png);
        }
        
        .right {
            color: green;
            background-image: url(images/right.png);
        }
    </style>
</head>

<body>
    <div class="register">
        <input type="password" class="ipt">
        <p class="message">Enter a password of 6 to 16 characters</p>
    </div>
    <script>
        // The first event to determine is that the form loses focus onblur
        // If the input is correct, the correct information will be displayed
        // If the input is not 6 to 16 bits, the error message will be displayed as a red small icon change
        // Since there are many changes in the style, we use className to modify the style
        // 1. Get the element
        var ipt = document.querySelector('.ipt');
        var message = document.querySelector('.message');
        //2. The registration event loses focus
        ipt.onblur = function() {
            // According to the length of the value in the form ipt.value.length
            if (this.value.length < 6 || this.value.length > 16) {
                // console.log(' error ');
                message.className = 'message wrong';
                message.innerHTML = 'The number of digits you entered does not require 6-16 digits';
            } else {
                message.className = 'message right';
                message.innerHTML = 'You typed it correctly'; }}</script>
Copy the code

4.5 Exclusivity

If we have the same set of elements and we want one element to implement a certain style, we need to use the exclusivity algorithm of the loop:

  1. Clear style of all elements (kill others)
  2. Styling the current element (leaving me)
  3. Don’t reverse the order. Kill others first, then set yourself

<body>
    <button>Button 1</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 [I]
        for (var i = 0; i < btns.length; i++) {
            btns[i].onclick = function() {
                // (1) We first remove all the buttons from the background color to kill everyone
                for (var i = 0; i < btns.length; i++) {
                    btns[i].style.backgroundColor = ' ';
                }
                // (2) Then make the current element background color leave myself for Pink
                this.style.backgroundColor = 'pink'; }}//2. Exclude others first and then set your own style
    </script>
</body>
Copy the code

Case: Baidu skin

Case analysis

This example exercises registering events for a set of elements

② Register click events for 4 small images in a loop

③ When we click on the image, change the background of our page to the current image

④ Core algorithm: take the SRC path of the current image and give the body as the background

    <style>
        * {
            margin: 0;
            padding: 0;
        }
        
        body {
            background: url(images/1.jpg) no-repeat center top;
        }
        
        li {
            list-style: none;
        }
        
        .baidu {
            overflow: hidden;
            margin: 100px auto;
            background-color: #fff;
            width: 410px;
            padding-top: 3px;
        }
        
        .baidu li {
            float: left;
            margin: 0 1px;
            cursor: pointer;
        }
        
        .baidu img {
            width: 100px; } </style> </head> <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. Var imgs = document.querySelector('.baidu').querySelectorAll('img'); // console.log(imgs); For (var I = 0; i < imgs.length; I ++) {imgs[I].onclick = function() {// this.src is the path where we clicked images/2.jpg // console.log(this.src); / / the path this. Just give the body the SRC document. The body. The style.css. BackgroundImage = 'url' (' + this. SRC + '); } } </script> </body>Copy the code

Case in point: Table discoloration on interlaced lines

Case analysis

Mouse over onMouseOver and mouse away from Onmouseout

Mouse over TR line, the current row changes the background color, mouse away to remove the current background color

③ Note: the first line (the line inside thead) does not need to change color, so we get the line inside tbody

table { width: 800px; margin: 100px auto; text-align: center; border-collapse: collapse; font-size: 14px; } thead tr { height: 30px; background-color: skyblue; } tbody tr { height: 30px; } tbody td { border-bottom: 1px solid #d7d7d7; font-size: 12px; color: blue; } .bg { background-color: pink; } < / style > < / head > < body > < table > < thead > < tr > < th > code < / th > < th > name < / th > < th > the latest net < / th > < th > accumulative total net value of < / th > < th > < / th > unit net value before Growth rate of net value of the < th > < / th > < / tr > < thead > < tbody > < tr > < td > 003526 < / td > < td > agricultural bank Jin Sui 3 months regular open bond < / td > < td > 1.075 < / td > < td > 1.079 < / td > 1.074 < / td > < td > < td > + 0.047% < / td > < / tr > < tr > < td > 003526 < / td > < td > agricultural bank Jin Sui 3 months regular open bond < / td > < td > 1.075 < / td > < td > 1.079 < / td > 1.074 < / td > < td > < td > + 0.047% < / td > < / tr > < tr > < td > 003526 < / td > < td > agricultural bank Jin Sui 3 months regular open bond < / td > < td > 1.075 < / td > < td > 1.079 < / td > 1.074 < / td > < td > < td > + 0.047% < / td > < / tr > < tr > < td > 003526 < / td > < td > agricultural bank Jin Sui 3 months regular open bond < / td > < td > 1.075 < / td > < td > 1.079 < / td > 1.074 < / td > < td > < td > + 0.047% < / td > < / tr > < tr > < td > 003526 < / td > < td > agricultural bank Jin Sui 3 months regular open bond < / td > < td > 1.075 < / td > < td > 1.079 < / td > 1.074 < / td > < td > < td > + 0.047% < / td > < / tr > < tr > < td > 003526 < / td > < td > agricultural bank Jin Sui 3 months regular open bond < / td > < td > 1.075 < / td > < td > 1.079 < / td > 1.074 < / td > < td > < td > + 0.047% < / td > < / tr > < / tbody > < / table > < script > / / 1. Var TRS = document.querySelector(' tBody ').querySelectorAll('tr'); For (var I = 0; i < trs.length; TRS [I]. Onmouseover = function() {// console.log(11); this.className = 'bg'; Onmouseout = function() {this.className = "";} // 4. } } </script> </body>Copy the code

Case: The case of selecting all and canceling all

Business requirements:

  1. Click the all check box above, all the check boxes below are selected (All)
  2. Click the All check box again, all of the following check boxes are not selected (deselect all)
  3. If all the boxes below are checked, the All button above is automatically checked
  4. If one of the following check boxes is not checked, the All button above is not checked
  5. All checkboxes are initially unchecked by default

Case analysis

① Select all and cancel all: let the checked properties of all the following check boxes (selected state) follow the select button

(2) Bind click events to all of the following check boxes, and each time you click, you need to loop to see if all of the following check boxes are unselected. If there is one unselected check box, all of the above will not be selected.

③ You can set a variable to control whether all is selected

<style>
        * {
            padding: 0;
            margin: 0;
        }
        
        .wrap {
            width: 300px;
            margin: 100px auto 0;
        }
        
        table {
            border-collapse: collapse;
            border-spacing: 0;
            border: 1px solid #c0c0c0;
            width: 300px;
        }
        
        th,
        td {
            border: 1px solid #d0d0d0;
            color: #404060;
            padding: 10px;
        }
        
        th {
            background-color: #09c;
            font: bold 16px Microsoft Yahei;
            color: #fff;
        }
        
        td {
            font: 14px Microsoft Yahei;
        }
        
        tbody tr {
            background-color: #f0f0f0;
        }
        
        tbody tr:hover {
            cursor: pointer;
            background-color: #fafafa;
        }
    </style>

</head>

<body>
    <div class="wrap">
        <table>
            <thead>
                <tr>
                    <th>
                        <input type="checkbox" id="j_cbAll" />
                    </th>
                    <th>goods</th>
                    <th>The price</th>
                </tr>
            </thead>
            <tbody id="j_tb">
                <tr>
                    <td>
                        <input type="checkbox" />
                    </td>
                    <td>iPhone8</td>
                    <td>8000</td>
                </tr>
                <tr>
                    <td>
                        <input type="checkbox" />
                    </td>
                    <td>iPad Pro</td>
                    <td>5000</td>
                </tr>
                <tr>
                    <td>
                        <input type="checkbox" />
                    </td>
                    <td>iPad Air</td>
                    <td>2000</td>
                </tr>
                <tr>
                    <td>
                        <input type="checkbox" />
                    </td>
                    <td>Apple Watch</td>
                    <td>2000</td>
                </tr>

            </tbody>
        </table>
    </div>
    <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'); // Select all button
        var j_tbs = document.getElementById('j_tb').getElementsByTagName('input'); // All check boxes below
        // Register events
        j_cbAll.onclick = function() {
                // this.checked Gets the checked status of the current checkbox if it is true and if it is false it is not checked
                console.log(this.checked);
                for (var i = 0; i < j_tbs.length; i++) {
                    j_tbs[i].checked = this.checked; }}// 2. Bind click events to all of the following check boxes. Each time you click, check whether all of the following check boxes are unselected.
        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; // Exit the for loop to improve the efficiency of the execution because if one is not selected, the rest of the loop does not need to judge} } j_cbAll.checked = flag; }}</script>
Copy the code

4.6 Operations for Customizing Attributes

1. Obtain the attribute value

Element. Property Gets the value of the property.

Element. The getAttribute (‘ property ‘);

The difference between:

Element. Attribute Gets the value of the built-in attribute (the element’s own attribute)

Element. The getAttribute (” properties “); Mainly get custom properties (standard) we programmers custom properties

2. Set the property value

Element. property = ‘value’ Sets the value of the built-in property.

Element.setattribute (‘ attribute ‘, ‘value ‘);

The difference between:

Element. property Sets the value of the built-in property

Element. The setAttribute (” properties “); Mainly set custom properties (standard)

3. Remove attributes

Element. The removeAttribute (‘ property ‘);

<body>
    <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'));
        // 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 name is className
        // 3 removeAttribute removeAttribute
        div.removeAttribute('index');
    </script>
</body>
Copy the code

Case: TAB bar switch (key case)

When the mouse clicks on the corresponding TAB above, the following changes

Case analysis

(1) There are two large modules for Tab bar switching

② on the module TAB, click on one of them, the current background color will be red, the rest of the same (exclusive thinking) to modify the class name

③ The contents of the following modules will change with the tabs above. So the following module changes are written to the click event.

④ Rule: the following modules display content and the above TAB one by one, match.

Add a custom attribute to all li’s in tab_list. The attribute values are numbered from 0.

⑥ When we click on a small li in tab_list, tab_con will display the contents corresponding to the sequence number, and the rest will be hidden.

<style>
        * {
            margin: 0;
            padding: 0;
        }
        
        li {
            list-style-type: none;
        }
        
        .tab {
            width: 978px;
            margin: 100px auto;
        }
        
        .tab_list {
            height: 39px;
            border: 1px solid #ccc;
            background-color: #f1f1f1;
        }
        
        .tab_list li {
            float: left;
            height: 39px;
            line-height: 39px;
            padding: 0 20px;
            text-align: center;
            cursor: pointer;
        }
        
        .tab_list .current {
            background-color: #c81623;
            color: #fff;
        }
        
        .item_info {
            padding: 20px 0 0 20px;
        }
        
        .item {
            display: none;
        }
    </style>
</head>

<body>
    <div class="tab">
        <div class="tab_list">
            <ul>
                <li class="current">The introduction</li>
                <li>Specifications and Packing</li>
                <li>After-sale protection</li>
                <li>Commodity Evaluation (50000)</li>
                <li>Mobile community</li>
            </ul>
        </div>
        <div class="tab_con">
            <div class="item" style="display: block;">Product introduction module content</div>
            <div class="item">Specifications and packaging module content</div>
            <div class="item">After-sales support module content</div>
            <div class="item">Product evaluation (50000) module content</div>
            <div class="item">Mobile community module content</div>

        </div>
    </div>
    <script>
        // Get the element
        var tab_list = document.querySelector('.tab_list');
        var lis = tab_list.querySelectorAll('li');
        var items = document.querySelectorAll('.item');
        // The for loop binds the click event
        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. Click on one of the modules TAB, the background color of the current one 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

4.7 H5 User-defined Attributes

The purpose of custom attributes is to save and use data. Some data can be saved to a page instead of a database.

Custom attributes are obtained using getAttribute(‘ attributes’).

However, some custom attributes can be ambiguous and it is not easy to determine whether they are built-in or custom attributes of an element.

H5 gives us new custom attributes:

1. Set H5 custom attributes

H5 specifies the custom attribute data- beginning as the attribute name and assigns a value.

Such as < div data – index = “1” > < / div >

Or use JS Settings

Element. The setAttribute (' data - the index, 2)

2. Obtain H5 custom attributes

  1. Getelement. GetAttribute (‘ data-index ‘);
  2. H5 update element.dataset. Index or Element. dataset[‘ index ‘] IE 11
<body>
    <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>
</body>
Copy the code

5. Perform node operations

5.1 Why Do I Learn Node Operations

There are two common ways to get elements:

1. Get elements using methods provided by DOM

document.getElementById()

document.getElementsByTagName()

Document. QuerySelector etc

Logic is not strong, cumbersome

2. Use node hierarchy to get elements

Elements are obtained by using the father-son and brother-son node relationships

Logical, but less compatible

Both methods can be used to get element nodes, which we’ll use later, but the node operation is simpler

5.2 Overview of Nodes

Everything in a web page is a node (tag, attribute, text, comment, etc.), and in the DOM, nodes are represented using Node. All nodes in the HTML DOM tree are accessible through JavaScript, and all HTML elements (nodes) can be modified, created or deleted.

In general, a node has at least three basic attributes: nodeType, nodeName, and nodeValue.

The element node nodeType is 1

Attribute node nodeType is 2

The text node nodeType is 3 (the text node contains text, Spaces, line feeds, and so on)

In our actual development, node operations operate primarily on element nodes

<body> <! -- Node advantages --><div>I am a div</div>
    <span>I am a span</span>
    <ul>
        <li>I'm li</li>
        <li>I'm li</li>
        <li>I'm li</li>
        <li>I'm li</li>
    </ul>
    <div class="box">
        <span class="erweima">x</span>
    </div>
    <script>
        var box = document.querySelector('.box');
        console.dir(box);
    </script>
</body>
Copy the code

5.3 Node Layers

DOM trees can be used to divide nodes into different hierarchies, and the most common one is father-son and brother-son hierarchies.

DOM trees can be used to divide nodes into different hierarchies, and the most common one is father-son and brother-son hierarchies.

1. Parent node

node.parentNode

The parentNode property returns the nearest parent of a node

Returns NULL if the specified node has no parent

<! -- Node advantages --><div>I am a div</div>
    <span>I am a span</span>
    <ul>
        <li>I'm li</li>
        <li>I'm li</li>
        <li>I'm li</li>
        <li>I'm li</li>
    </ul>
    <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

2. The child nodes

  1. Parentnode. childNodes (Standard)

Parentnode. childNodes returns an updated collection of children of the specified node.

Note: The return value contains all child nodes, including element nodes, text nodes, and so on.

If you only want to get inside element nodes, you need to do this. So childNodes is generally not recommended

  1. Parentnode. children (non-standard)

Parentnode. children is a read-only property that returns all child element nodes. It returns only the child node, not the rest of the node (this is our focus).

Although children is non-standard, it is supported by all browsers, so we can use it with confidence

<! -- Node advantages --><div>I am a div</div>
    <span>I am a span</span>
    <ul>
        <li>I'm li</li>
        <li>I'm li</li>
        <li>I'm li</li>
        <li>I'm li</li>

    </ul>
    <ol>
        <li>I'm li</li>
        <li>I'm li</li>
        <li>I'm li</li>
        <li>I'm li</li>
    </ol>

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

    <script>
        // Get the method (API) provided by DOM
        var ul = document.querySelector('ul');
        var lis = ul.querySelectorAll('li');
        // 1. ChildNodes childNodes all childNodes contain element nodes text nodes and so on
        console.log(ul.childNodes);
        console.log(ul.childNodes[0].nodeType);
        console.log(ul.childNodes[1].nodeType);
        // 2. Children get all the child element nodes
        console.log(ul.children);
    </script>
Copy the code
  1. parentNode.firstChild

FirstChild returns the firstChild, or null if not found. Again, it contains all nodes.

  1. parentNode.lastChild

LastChild returns the lastChild, or null if not found. Again, it contains all nodes.

  1. parentNode.firstElementChild

FirstElementChild returns the first child node, or null if not found.

  1. parentNode.lastElementChild

LastElementChild returns the last child node, or null if not found.

Note: These two methods have compatibility issues and are only supported in IE9.

    <ol>
        <li>I am a li1</li>
        <li>I am a li2</li>
        <li>I am li3</li>
        <li>I am a li4</li>
        <li>I am a li5</li>
    </ol>
    <script>
        var ol = document.querySelector('ol');
        // 1. firstChild the firstChild of either a text node or an element node
        console.log(ol.firstChild);
        console.log(ol.lastChild);
        // 2. FirstElementChild returns the first child node supported only by IE9
        console.log(ol.firstElementChild);
        console.log(ol.lastElementChild);
        // 3. The actual developed notation has no compatibility issues and returns the first child
        console.log(ol.children[0]);
        console.log(ol.children[ol.children.length - 1]);
    </script>
Copy the code

In practice, firstChild and lastChild contain other nodes, which is inconvenient, and firstElementChild and lastElementChild have compatibility issues. How do we get the first or lastChild node?

Solution:

  1. You can use this if you want the first child element nodeparentNode.chilren[0]
  2. You can use this if you want the last child element nodeparentNode.chilren[parentNode.chilren.length - 1]

Example: drop-down menu

Case analysis

(1) The li in the navigation bar should have a mouse pass effect, so you need to register the mouse event cycle

② Core principle: when the mouse passes over li inside the second child UL display, when the mouse left, ul hidden implementation code

<ul class="nav">
        <li>
            <a href="#">weibo</a>
            <ul>
                <li>
                    <a href="">Direct messages</a>
                </li>
                <li>
                    <a href="">comments</a>
                </li>
                <li>
                    <a href="">@ I</a>
                </li>
            </ul>
        </li>
        <li>
            <a href="#">weibo</a>
            <ul>
                <li>
                    <a href="">Direct messages</a>
                </li>
                <li>
                    <a href="">comments</a>
                </li>
                <li>
                    <a href="">@ I</a>
                </li>
            </ul>
        </li>
        <li>
            <a href="#">weibo</a>
            <ul>
                <li>
                    <a href="">Direct messages</a>
                </li>
                <li>
                    <a href="">comments</a>
                </li>
                <li>
                    <a href="">@ I</a>
                </li>
            </ul>
        </li>
        <li>
            <a href="#">weibo</a>
            <ul>
                <li>
                    <a href="">Direct messages</a>
                </li>
                <li>
                    <a href="">comments</a>
                </li>
                <li>
                    <a href="">@ I</a>
                </li>
            </ul>
        </li>
    </ul>
    <script>
        // 1. Get the element
        var nav = document.querySelector('.nav');
        var lis = nav.children; // Get four little Li's
        // 2. Loop the register 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>
Copy the code

5.3 Node Layers

3. Sibling nodes

  1. node.nextSibling

NextSibling returns the nextSibling of the current element, or null if it cannot be found. Again, it contains all nodes.

  1. node.previousSibling

PreviousSibling Returns a sibling node on the current element, or null if it cannot be found. Again, it contains all nodes.

  1. node.nextElementSibling

NextElementSibling Returns the next sibling of the current element, or null if it cannot be found.

  1. node.previousElementSibling

PreviousElementSibling Returns a sibling on the current element, or null if it cannot be found. Note: These two methods have compatibility issues and are only supported in IE9.

< div > I am a div < / div ><span>I am a span</span>
    <script>
        var div = document.querySelector('div');
        // 1. NextSibling the nextSibling contains element nodes, text nodes, etc
        console.log(div.nextSibling);
        console.log(div.previousSibling);
        // 2. NextElementSibling get the next sibling node
        console.log(div.nextElementSibling);
        console.log(div.previousElementSibling);
    </script>
Copy the code

Q: How do I resolve compatibility issues?

A: Encapsulate a compatibility function yourself

Sibling nodes are not often used in normal development

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

5.4 Creating a Node

document.createElement(‘tagName’)

The document.createElement() method creates the HTML element specified by tagName. Because these elements do not originally exist and are dynamically generated according to our requirements, we also call them dynamically created element nodes.

5.4 Adding a Node

  1. node.appendChild(child)

The node.appendChild() method adds a node to the end of the list of children of the specified parent node. Similar to the after pseudo-element in CSS.

  1. Node.insertbefore (child, specify element)

The node.insertbefore () method adds a node before the specified children of the parent node. This is similar to the before element in CSS.

    <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 similar to push in an array
        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>
Copy the code

Case: Simple version release message case

Case analysis

Click the button to dynamically create a LI and add it to ul.

Insert the value of the text field into li.innerHTML

InsertBefore = insertBefore = insertBefore = insertBefore

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

    </ul>
    <script>
        // 1. Get the element
        var btn = document.querySelector('button');
        var text = document.querySelector('textarea');
        var ul = document.querySelector('ul');
        // 2. Register events
        btn.onclick = function() {
            if (text.value == ' ') {
                alert('You did not enter anything');
                return false;
            } else {
                // console.log(text.value);
                // (1) Create element
                var li = document.createElement('li');
                // Li can be assigned first
                li.innerHTML = text.value;
                // (2) Add elements
                // ul.appendChild(li);
                ul.insertBefore(li, ul.children[0]); }}</script>
Copy the code

5.5 Deleting a Node

node.removeChild(child)

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

< 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>
Copy the code

Case: Deleting a message

Case analysis

① When we assign a value from the text field to Li, add a delete link

② We need to get all the links. When we click the current link, delete the li where the current link is

Add javascript:void(0); Or javascript:;

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

    </ul>
    <script>
        // 1. Get the element
        var btn = document.querySelector('button');
        var text = document.querySelector('textarea');
        var ul = document.querySelector('ul');
        // 2. Register events
        btn.onclick = function() {
            if (text.value == ' ') {
                alert('You did not enter anything');
                return false;
            } else {
                // console.log(text.value);
                // (1) Create element
                var li = document.createElement('li');
                // Li can be assigned first
                li.innerHTML = text.value + " delete < / a >";
                // (2) Add elements
                // ul.appendChild(li);
                ul.insertBefore(li, ul.children[0]);
                // (3) Delete element deletes the parent of the current link li
                var as = document.querySelectorAll('a');
                for (var i = 0; i < as.length; i++) {
                    as[i].onclick = function() {
                        // node.removeChild(child); ParentNode = this.parentNode = this.parentNode;
                        ul.removeChild(this.parentNode); }}}}</script>
Copy the code

Example: Dynamically generating tables

Case analysis

① Because the student data inside is dynamic, we need JS dynamic generation. Here we simulate the data and define the data ourselves. We store data as objects.

② All data is placed in the row inside the Tbody.

③ Because there are many rows, we need to loop to create multiple rows (corresponding to how many people).

④ There are many cells in each row (corresponding to the data in the row), and we continue to use the loop to create multiple cells and store the data in the row (double for loop).

⑤ The last column of cells is deleted, and a separate cell needs to be created.

⑥ Add and delete the current row. Click Delete to delete the current row.

    <table cellspacing="0">
        <thead>
            <tr>
                <th>The name</th>
                <th>subjects</th>
                <th>results</th>
                <th>operation</th>
            </tr>
        </thead>
        <tbody>

        </tbody>
    </table>
    <script>
        // 1. Prepare students' data first
        var datas = [{
            name: 'Wei Yingluo'.subject: 'JavaScript'.score: 100
        }, {
            name: 'hong li'.subject: 'JavaScript'.score: 98
        }, {
            name: 'Fu Heng'.subject: 'JavaScript'.score: 99
        }, {
            name: 'MingYu'.subject: 'JavaScript'.score: 88
        }, {
            name: 'Big pig trotter'.subject: 'JavaScript'.score: 0
        }];
        // 2. Create a row in tBody: We will create a few rows for the number of people (by the length of the array)
        var tbody = document.querySelector('tbody');
        for (var i = 0; i < datas.length; i++) { // Line tr for loop outside
            // 1. Create the tr line
            var tr = document.createElement('tr');
            tbody.appendChild(tr);
            For loop through datas[I]; for loop through datas[I]
            for (var k in datas[i]) { // inside the for loop column td
                // Create a cell
                var td = document.createElement('td');
                // Add datas[I][k] to td
                // console.log(datas[i][k]);
                td.innerHTML = datas[i][k];
                tr.appendChild(td);
            }
            // 3. Create cell with delete 2 words
            var td = document.createElement('td');
            td.innerHTML = ' delete < / a > ';
            tr.appendChild(td);

        }
        // 4. The deletion operation begins
        var as = document.querySelectorAll('a');
        for (var i = 0; i < as.length; i++) {
            as[i].onclick = function() {
                Node.removechild (child)
                tbody.removeChild(this.parentNode.parentNode)
            }
        }
        // for(var k in obj) {
        // k returns the attribute name
        // obj[k] gets the attribute value
        // }
    </script>
Copy the code

5.8 Three dynamically created element differences

document.write()

element.innerHTML

document.createElement()

The difference between

  1. Document.write is a content flow that writes directly to the page, but when the document flow completes, it causes the page to be completely redrawn
  2. InnerHTML writes content to a DOM node without causing the page to be completely redrawn
  3. InnerHTML creates multiple elements more efficiently (instead of concatenating strings, concatenate them as arrays) and has a slightly more complex structure
  4. CreateElement () creates multiple elements slightly less efficiently, but with a cleaner structure
Click < button > < / button ><p>abc</p>
    <div class="inner"></div>
    <div class="create"></div>
    <script>
        // window.onload = function() {
        // document.write('
        
123
');
/ /} // There are three different ways to create elements // 1.document.write () create element If the page document flow has been loaded, calling this statement will cause the page to be redrawn // var btn = document.querySelector('button'); // btn.onclick = function() { // document.write('
123
');
// } // 2. InnerHTML creates the element var inner = document.querySelector('.inner'); // for (var i = 0; i <= 100; i++) { // inner.innerhtml += ' // } var arr = []; for (var i = 0; i <= 100; i++) { arr.push('); } inner.innerHTML = arr.join(' '); // 3. Document.createelement () creates the element var create = document.querySelector('.create'); for (var i = 0; i <= 100; i++) { var a = document.createElement('a'); create.appendChild(a); }
</script>
Copy the code

Summary: innerHTML is more efficient than creatElement in different browsers

6. DOM focuses on the core

Document Object Model (DOM) is a standard programming interface recommended by W3C to deal with extensible markup language (HTML or XML). The W3C has defined a set of DOM interfaces that allow you to change the content, structure, and style of a web page.

  1. For JavaScript, to enable JavaScript to manipulate HTML, JavaScript has its own DOM programming interface.
  2. In the case of HTML, DOM causes the HTML to form a DOM tree. Contains documents, elements, and nodes

The DOM element we get is an object, so it is called the Document Object Model

With respect to DOM manipulation, we focus on manipulation of elements.

There are mainly create, add, delete, change, check, attribute operation, event operation.

6.1 create

  1. document.write
  2. innerHTML
  3. createElement

6.2 to add

  1. appendChild
  2. insertBefore

6.3 delete

  1. removeChild

6.4 change

Mainly modify dom element attributes, CONTENT of DOM elements, attributes, form values, etc

  1. Modify element attributes: SRC, href, title, etc
  2. Modify the innerHTML and innerText of a normal element
  3. Modify form elements: Value, Type, disabled, etc
  4. Modify the element styles: style, className

6.5 check

Basically get the elements of the query DOM

  1. API methods provided by DOM: getElementById, getElementsByTagName Older usage is not recommended
  2. H5 provides new methods: querySelector, querySelectorAll advocate
  3. Use node operation to obtain elements: parentNode, children, sibling (previousElementSibling, nextElementSibling) advocacy

6.6 Attribute Operations

This applies primarily to custom attributes.

  1. SetAttribute: Sets the DOM attribute value
  2. GetAttribute: Gets the DOM attribute value
  3. RemoveAttribute Removes an attribute

6.7 Event Operations

Register an event for the element, taking the event source. Event type = event handler