JavaScript — DOM operation + case demonstration

Time:2021-4-30

1introduce

When a web page is loaded, the browser will create a document object model of the page. The DOM standard stipulates that each member in an HTML document is a node. The HTML DOM tree is shown in the following figure

2Find node

1. Direct search
Document. Getelementbyid # get a unique tag based on ID
Document. Getelementsbyclassname # gets a series of tags according to the class attribute
Document. GetElementsByTagName # get a series of tags according to the tag name
2. Indirect search
ChildNodes # gets all the child nodes, including elements and text
Children # gets all element child nodes, excluding text
Parentnode # get parent node
Previoussibling # gets the previous sibling node, which contains the text
Previouselementsibling # gets the previous sibling element node, which does not contain text
Nextsibling # gets the next sibling node, which contains the text
Nexterelementsibling # gets the next sibling node without text
Firstchild # gets the first child node, which contains the text
Firstelementchild # gets the first child node without text
Lastchild # gets the last child node containing text
Lastelementchild # gets the last element node of the parent element. Does not contain text

3. Examples

JavaScript -- DOM operation + case demonstrationJavaScript -- DOM operation + case demonstration

Title
    

    


111
2222


    aaaa
    111
    bbb
    2222
    ccc

aaaaaaaaaaaaaaa



    //Var box3 = document. Getelementbyid ("BTN") // find by ID, recommended (search basis for JS adding effect)
    // console.log(box3)
    //Var box = document. Getelementsbyclassname ("box") // find by class name
    // console.log(box)
    // console.log(box[1])
    //Var box = document. GetElementsByTagName ('div ') // find by tag
    // console.log(box.length)
    // console.log(box[2])
    //Var box = document. Getelementsbyname ("XXX") // find it through the name attribute
    // console.log(box.length)
    // console.log(box[1])

    //Var res1 = document. Getelementbyid ("BTN"). ChildNodes // find all sons (with text)
    // console.log(res1)
    //Var res2 = document. Getelementbyid ("BTN"). Children // find all sons (without text)
    // console.log(res2)
    //Var res3 = document. Getelementbyid ("BTN"). Parentnode // find parent
    // console.log(res2)
    //Var res4 = document. Getelementbyid ("BTN"). Nextsibling // find the next brother (with text)
    //Var res5 = document. Getelementbyid ("BTN"). Nexterementsibling // find the next brother (without text)

    //Var res6 = document. Getelementbyid ("BTN"). Previouselementsibling // only find the previous sibling tag (without text)

    //Var res7 = document. Getelementbyid ("BTN"). Firstelementchild // find the first son (without text)
    //Var res7 = document. Getelementbyid ("BTN"). Firstchild // find the first son (with text)

     // var res7=document.getElementById("btn").lastElementChild
    // var res7=document.getElementById("btn").lastChild
    // console.log(res7)

application

 

3、 Add, delete, change, change node, get element value

1. Add node

#1. Create a new node
var divEle = document.createElement('div');

#2. Append a child node (to the end)
Somenode. AppendChild (new child node);

#3. Insert a child node (before a node)
Somenode. InsertBefore (new child node, a node);

2、Delete and replace nodes

Somenode. Removechild (the child node to be deleted);
Somenode. Replacechild (new child node, a child node);

3. Examples

JavaScript -- DOM operation + case demonstrationCase: add, delete and replace

4、Modify / set node properties

#1. Get the value of the text node:
var divEle = document.getElementById("d1")
divEle.innerText
divEle.innerHTML

#2. Set the value of the text node:
var divEle = document.getElementById("d1")
Divele. InnerText = "1" // even if the label is placed, it can only be parsed into text
Divele. InnerHTML = "2" // can parse text and Tags

#3. Attribute operation
var divEle = document.getElementById("d1");
divEle.setAttribute("age","18")
divEle.getAttribute("age")
divEle.removeAttribute("age")

#4. The built-in property can also be obtained and set directly by the. Property name
imgEle.src
imgEle.src="..."

 

5、Gets the value of the element

#It is suitable for input, select and textarea tags

var x=document.getElementById('input')
var y=document.getElementById('select')
var z=document.getElementById('textarea')

x.value
y.value
z.value

6. Examples

JavaScript -- DOM operation + case demonstrationCase: change, get the value of the element

 

7Class operation

var x=document.getElementById('div1')

x.classList.remove('col1')
x.classList.add('col1')
x.classList.contains('col1')
x.classList.toggle('col1')

give an example:

JavaScript -- DOM operation + case demonstrationJavaScript -- DOM operation + case demonstration

Title
    
        div {
            width: 200px;
            height: 200px;
            border: 1px solid red;
        }
        .box {
            background-color: red;
        }

        .box3 {
            width: 300px;
            height: 300px;
        }
    


11111

2222

3333

    // var arr=document.getElementsByTagName('div')
    // for (var i=0;i<arr.length;i++){
    //     arr[i].classList.add("box")
    // }

    // var oDiv=document.getElementsByClassName("box3")[0]
    // oDiv.classList.remove('box3')

    // var oDiv=document.getElementsByClassName("box3")[0]
    // alert(oDiv.classList.contains("box3"))

    // var oDiv=document.getElementsByTagName("div")[2]
    // oDiv.classList.toggle("box3")

usage

 

8CSS operation

obj.style.backgroundColor="red"

The rules of CSS attribute operation in JS are as follows:

1. For CSS attributes without middle line, you can use style. Attribute name directly. For example:

obj.style.margin
obj.style.width
obj.style.left
obj.style.position

2. For CSS attributes with middle horizontal line, change the first letter after middle horizontal line into upper case. For example:

obj.style.marginTop
obj.style.borderLeftWidth
obj.style.zIndex
obj.style.fontFamily

9event

One of the new features of HTML 4.0 is the ability to make HTML events trigger actions in the browser, such as executing a JavaScript when a user clicks an HTML element.

The following is a list of properties that can be inserted into HTML tags to define event actions.

1. Common events

Onclick the event handle that is called when the user clicks on an object.
The event handle that is called when the user double clicks an object.

The onfocus element gets the focus// Exercise: input box
The onblur element loses focus. Application scenario: used for form verification. When the user leaves an input box, it means that the input has been finished, and we can verify it
The content of onchang domain is changed. Application scenario: usually used for form elements, triggered when the element content is changed. (select linkage)

One of the keyboard keys is pressed. Application scenario: when the user presses enter in the last input box, the form is submitted
Onkeypress a key is pressed and released.
Onkeyup a keyboard key is released.
Onload a page or an image to complete the loading.
The onmousedown mouse button is pressed.
OnMouseMove mouse is moved.
Onmouseout move the mouse away from an element.
OnMouseOver mouse over an element.

Onselect occurs when the text in the text box is selected.
The onsubmit confirmation button is clicked and the object used is the form.

2. Binding mode

//Method 1:
I'm Div. I'll go to your sister's and order me

  function changeColor(ths) {
    ths.style.backgroundColor="green";
  }


be careful:
This is an argument that represents the current element that triggers the event.
Ths is a formal parameter in the process of function definition.

//Method 2:
Come on, light up my green

    var oDiv = document.getElementById('div1');
    oDiv.onclick = function() {
        this.style.backgroundColor = 'red';
    }

10、 Cases

1. Case 1: modal box

slightly

2. Case 2: Click to have surprise

JavaScript -- DOM operation + case demonstrationJavaScript -- DOM operation + case demonstration

Document
    
        * {
            margin: 0;
            padding: 0;
        }

        .box {
            width: 200px;
            height: 200px;
            background: red;
            text-align: center;
            color: white;
            line-height: 200px;
            font-size: 23px;
            font-weight: bold;
            margin: 20px auto;
        }
    


Click to have surprise!!!

    var oBox = document.getElementsByClassName('box')[0];

    //The number of initial clicks. Change the style of DOM by increasing the number of times
    var a = 0;
    oBox.onclick = function () {
        a++;
        console.log(a % 4);
        if (a % 4 === 1) {
            this.style.background = 'green';
            This. InnerText ='continue to click! ';
        } else if (a % 4 == 2) {
            this.style.background = 'blue';
            This. InnerText ='fool you ';
        } else if (a % 4 == 3) {
            this.style.background = 'transparent';
            this.innerText = '';
        } else {
            this.style.background = 'red';
            this.innerText = 'Click to have surprise!!!';
        }

    }

Case 2: Click to have surprise

 

 

3. Case 3: simple comment board

JavaScript -- DOM operation + case demonstrationJavaScript -- DOM operation + case demonstration

Document
    
        * {
            margin: 0;
            padding: 0;
        }

        #comment {
            background-color: #b0b0b0;
            width: 500px;
        }

        #comment ul li {
            list-style: none;
            background-color: wheat;
            border: 1px dashed #000;
            margin: 0px 10px 10px;
            word-break: break-all;
            word-wrap: break-word;
        }
    



    Comments:


    Message content:
    
    
        
        
    


    var comment = document.getElementById('comment');
    var box = document.getElementById('box');
    var submit = document.getElementById('submit');
    var content = document.getElementById('content');
    var btn = document.getElementById('btn');
    var calculate=document.getElementById('calculate');

    var ul = document.createElement('ul');
    comment.appendChild(ul);

    var count=0;
    btn.onclick = function () {
        var val = content.value;
        if (val.length != 0) {
            var date = new Date();
            var subTime = date.toLocaleString();

            var li = document.createElement('li');
            var p1 = document.createElement('h3');
            var p2 = document.createElement('p');

            var spans = document.getElementsByClassName('del');
            count=spans.length+1;

            P1. InnerHTML = '#' + '< span >' + count + '< / span >' + 'floor' + '     '+ subTime + '<span>      Delete < / span > ';
            p2.innerHTML = val;
            li.appendChild(p1);
            li.appendChild(p2);

            ul.appendChild(li);
            content.value = '';
        }

        function aa() {
            var spans = document.getElementsByClassName('del');
            for (var i = 0; i < spans.length; i++) {
                spans[i].onclick=function (currentIndex) {
                    function bb() {
                        ul.removeChild(this.parentNode.parentNode);
                        count--;
                        var ss=document.getElementsByClassName('num');
                        for (var j=currentIndex;j<ss.length;j++){
                            ss[j].innerHTML=parseInt(ss[j].innerHTML)-1;
                        }
                        aa();
                    }
                    return bb;

                }(i);
            }
        }
        aa()

    };

    calculate.onclick = function () {
        Alert ('a total of '+ count +' comments' were posted ');
    }

Case 3: simple comment board

4. Case 4: tab

JavaScript -- DOM operation + case demonstrationJavaScript -- DOM operation + case demonstration

Document
    
        * {
            margin: 0;
            padding: 0;
        }
        .tab {
            width: 480px;
            height: 200px;
            border: 1px solid red;
            margin: 0 auto;
        }

        ul li {
            list-style: none;
            width: 160px;
            height: 60px;
            line-height: 60px;
            text-align: center;
            background-color: #b0b0b0;
            float: left;
        }

        li.active {
            background-color: #55BBBB;
        }
        p {
            display: none;
            height: 200px;
            text-align: center;
            line-height: 200px;
            background-color: white;
        }
        p.active {
            display: block;
        }
    



    
        home page
        Journalism
        picture
    
    home page内容
    Journalism内容
    picture内容


    var aLi=document.getElementsByTagName('li');
    var aP=document.getElementsByTagName('p');
    for (var i=0;i<aLi.length;i++){
        aLi[i].index=i;
        aLi[i].onclick=function () {
            for (var j=0;j<aLi.length;j++){
                aLi[j].className='';
                aP[j].className='';
            }
            this.className='active';
            aP[this.index].className='active';
        }
    }

Case 4: tab

 

 

5. Case 5: imitating Taobao Search box

JavaScript -- DOM operation + case demonstrationJavaScript -- DOM operation + case demonstration

Document
    
        * {
            margin: 0;
            padding: 0;
        }

        #search {
            position: relative;
        }

        input {
            outline: none;
            display: block;
            border: 2px solid #f2a83c;
            border-radius: 10px;
            width: 490px;
            height: 50px;
            margin-top: 20px;
        }

        label {
            position: absolute;
            top: 20px;
            left: 10px;
            font-size: 8px;
            color: gray;
        }
    



    
    The clothes you want



    var txt = document.getElementById('text');
    var msg = document.getElementById('msg');

    //When detecting user form input
    txt.oninput = function () {
        //Control element display and hide
        if (this.value == '') {
            msg.style.display = 'block';
        } else {
            msg.style.display = 'none';
        }
    }

Case 5: imitating Taobao Search box

 

6. Case 6: get the current time

JavaScript -- DOM operation + case demonstrationJavaScript -- DOM operation + case demonstration

Document





    setInterval(function () {

        var date = new Date();

        var y = date.getFullYear();
        var m = date.getMonth();
        var d = date.getDate();
        var h = date.getHours();
        var min = date.getMinutes();
        var s = date.getSeconds();

        //Today is February 23, 2018, 8:23:09


        Document.body.innerhtml = "today is" + y + 'year' + num (M + 1) + "month" + num (d) + "day" + num (H) + ":" + num (min) + ":" + num (s)

    }, 1000)

    function num(n) {
        if (n < 10) {
            return "0" + n;

        }
        return n
    }

Case 6: get the current time

 

7. Case 7: uniform motion

JavaScript -- DOM operation + case demonstrationJavaScript -- DOM operation + case demonstration

Document
    
        * {
            padding: 0;
            margin: 0;
        }

        .box {
            width: 200px;
            height: 200px;
            background-color: #FF0000;
            position: absolute;
            top: 50px;
            left: 0px;
        }
    




    forward
    back off
    

    




    var btn1 = document.getElementById('btn1');
    var btn2 = document.getElementById('btn2');

    var box1 = document.getElementById('box1')

    var count = 0;
    var time1 = null;
    var time2 = null;

    btn1.onclick = function () {
        clearInterval(time2);

        time1 = setInterval(function () {
            count += 10;
            if (count > 1000) {
                box1.style.left = '1000px';
                box1.style.borderRadius = '50%';

                clearInterval(time1);
            } else {
                box1.style.left = count + 'px';
                box1.style.borderRadius = count / 2000 * 100 + '%';
            }


        }, 10)

    };
    btn2.onclick = function () {
        clearInterval(time1);
        time2 = setInterval(function () {
            count -= 10;
            if (count <= 0) {
                box1.style.left = '0px';
                box1.style.borderRadius = '';

                clearInterval(time2);
            } else {
                box1.style.left = count + 'px';
                box1.style.borderRadius = count / 2000 * 100 + '%';
                ;

            }


        }, 10)

    }

Case 7: uniform motion

 

8. Case 8: close the advertisement after 5S

JavaScript -- DOM operation + case demonstrationJavaScript -- DOM operation + case demonstration

Document
    
        * {
            padding: 0;
            margin: 0;
        }

        img {
            position: fixed;
            width: 300px;
        }

        ul {
            list-style: none;
        }

        #left {
            left: 0;
        }

        #right {
            right: 0;
        }

        ul li {
            font-size: 25px;
        }
    





    Dragon killing sword, click to send
    Dragon killing sword, click to send
    Dragon killing sword, click to send
    Dragon killing sword, click to send
    Dragon killing sword, click to send
    Dragon killing sword, click to send
    Dragon killing sword, click to send
    Dragon killing sword, click to send
    Dragon killing sword, click to send
    Dragon killing sword, click to send
    Dragon killing sword, click to send
    Dragon killing sword, click to send
    Dragon killing sword, click to send
    Dragon killing sword, click to send
    Dragon killing sword, click to send
    Dragon killing sword, click to send
    Dragon killing sword, click to send
    Dragon killing sword, click to send
    Dragon killing sword, click to send
    Dragon killing sword, click to send
    Dragon killing sword, click to send
    Dragon killing sword, click to send
    Dragon killing sword, click to send
    Dragon killing sword, click to send
    Dragon killing sword, click to send
    Dragon killing sword, click to send
    Dragon killing sword, click to send
    Dragon killing sword, click to send
    Dragon killing sword, click to send
    Dragon killing sword, click to send




    window.onload = function () {
        var left = document.getElementById('left');
        var right = document.getElementById('right');

        setTimeout(function () {
            left.style.display = 'none';
            right.style.display = 'none';


        }, 5000)
    }

Case 8: auto close ads after 5S

 

9. Case 9: Xiaomi rolling

JavaScript -- DOM operation + case demonstrationJavaScript -- DOM operation + case demonstration

Document
    
        * {
            padding: 0;
            margin: 0;
        }

        .wrap {
            width: 512px;
            height: 400px;
            border: 3px solid #808080;
            position: relative;
            overflow: hidden;
            margin: 100px auto;
        }

        .wrap span {
            width: 100%;
            height: 200px;
            position: absolute;
            background-color: transparent;
            border: 1px solid #000;
        }

        .up {
            top: 0;
        }

        .down {
            bottom: 0;
        }

        img {
            position: absolute;
            top: 0;
            left: 0;
            height: 200px;
        }
    



    

    11111

    22222





    var up = document.getElementById('picUp');
    var down = document.getElementById('picDown');

    var img = document.getElementById('xiaomi');

    var count = 0;
    var time = null;
    //When the mouse moves in
    up.onmouseover = function () {

        //Anyway, come up and clear the timer first
        clearInterval(time);
        time = setInterval(function () {
            count -= 3;

            count >= -1070 ? img.style.top = count + 'px' : clearInterval(time);


        }, 30)
    };
    down.onmouseover = function () {
        clearInterval(time);

        time = setInterval(function () {
            count += 1;

            count < 0 ? img.style.top = count + 'px' : clearInterval(time);


        }, 30)
    }

Case 9: picture scrolling up and down

 

10. Case 10: seamless carousel

JavaScript -- DOM operation + case demonstrationJavaScript -- DOM operation + case demonstration

Document
    
        * {
            padding: 0;
            margin: 0;
        }

        ul {
            list-style: none;
        }

        .box {
            width: 600px;
            height: 700px;
            margin: 50px auto;
            overflow: hidden;
            position: relative;
            border: 1px solid #000;

        }

        ul li {
            float: left;
        }

        .box ul {
            width: 500%;
            position: absolute;
            top: 0;
            left: 0;


        }
        img {
            width: 600px;
        }
    



    
        
        
        
        
        

    





    var box = document.getElementsByClassName('box')[0];

    var ul = box.children[0];
   

    var num = 0;
    var timer = null;

    timer = setInterval(autoPlay, 3);

    //Declaration of function
    function autoPlay() {
        num--;


        num <= -2400? num = 0: num;
        ul.style.left = num + 'px'

    }

    //Move the mouse up
    box.onmouseover = function () {
        clearInterval(timer)
    };
    box.onmouseout = function () {
        timer = setInterval(autoPlay, 3);
    }

Case 10: seamless carousel

 

Recommended Today

Large scale distributed storage system: Principle Analysis and architecture practice.pdf

Focus on “Java back end technology stack” Reply to “interview” for full interview information Distributed storage system, which stores data in multiple independent devices. Traditional network storage system uses centralized storage server to store all data. Storage server becomes the bottleneck of system performance and the focus of reliability and security, which can not meet […]