JavaScript summary 3.0— Document Object Model(DOM)

    1. Use DOM to get elements

    Get common elements

    • Get by ID: document.getElementById('')
    • Obtain by tag name: document.getElementsByTagName('') Note that what is returned is a pseudo-array, remember to add a subscript to get a specific element
    • Get by class name: document.getElementsByClassName('') returns a pseudo-array
    • Through querySelector: document.querySelector('symbol+selector') returns the first element object of the specified selector, which needs to be marked with . #
    • Return all element object collection of the specified selector via querySelectorAll() (return pseudo-array)

    Get special elements body, HTML
    Get the body element: document.body
    Get html element: document.documentElement


    2. Custom attribute operation

    Set custom attributes: element.setAttribute('attribute', 'value')
    Get custom attributes: element.getAttribute('attribute')
    Remove custom attribute: element.removeAttribute('attribute')

    <div></div>
    <script>
    var div = document.querySelector('div')
      div.setAttribute('myIndex',1);
       console.log( div.getAttribute('myIndex'));//1
       div.removeAttribute('myIndex');
       console.log( div.getAttribute('myIndex'));//null
    </script>
    

    Custom attributes are mostly used to set the index value for the li of ul

    H5's custom attribute: H5 stipulates that the custom attribute starts with data- as the attribute name and assigns a value

    H5 custom attributes can be obtained with element.getAttribute('attribute'), or element.dataset.attribute name (that is, the value after data-) or element.dataset['attribute name'] (These two methods are only supported by IE11) If the H5 custom attribute name has multiple -linked words, use hump nomenclature when obtaining

    <div data-index="1" data-list-name="f"></div>
     <script>
         var div = document. querySelector('div');
         console.log(div.getAttribute('data-index'));//1
         console.log(div.getAttribute('data-list-name'));//f
         // dataset is a collection that stores all custom attributes starting with data
         console.log(div.dataset);
         console.log(div.dataset.list-name);//NaN
         console.log(div.dataset.listName);//f
         console.log(div.dataset['listName']);//f
     </script>
    


    3. Node operation

    parent node

    Get the parent node: node.parentNode, returns the nearest parent node of a node, or null if no parent node is found

    <div class="grandpa">
     <div class="father">
         <span class="son"></span>
     </div>
    </div>
    <script>
     var son = document. querySelector('.son');
     console.log(son.parentNode); //return father node
     console.log(son.parentNode.parentNode);//return grandpa node
    </script>
    


    child nodes

    parentNode.childNodes returns a collection of child nodes containing the specified node, including element nodes, text nodes, etc. (almost never used)
    parentNode.children returns all sub-element node collections (pseudo-array form), key points


    Brother nodes

    node.nextSibling: returns the next sibling node of the current element, including all nodes (rarely used)
    node.previousSibling: returns the previous sibling node of the current element, including all nodes (use less)
    node.nextElementSibling returns the next sibling node of the current element
    node.previousElementSibling: returns the previous sibling node of the current element


    create node

    document. createElement('tagName')

    Batch manipulation of dom via createDocumentFragment or innerHTML will make performance better innerHTML is to write content to a DOM node, which will not cause the entire page to be redrawn

    Use innerHTML:

    function fn() {
         var str = '';
         for (var i = 0; i < 1000; i++) {
             str += `<a href="">use innerHTML</a>`
         }
         document.body.innerHTML = str
         //It is recommended to concatenate all the strings first and then assign them to the elements at one time, so that the performance is better than assigning each time
     }
    

    Use Document.createDocumentFragment(): first add all the nodes in the fragment and assign them to the parent element(using document fragments usually results in better performance.)

    function fn2() {
        var fragment = document.createDocumentFragment()
        for (var i = 0; i < 1000; i++) {
           var li = document.createElement('li')
           li.innerHTML = `<a href="">link</a>`
            fragment.appendChild(li)
        }
       document.body.appendChild (fragment)
    }
    


    add node

    node.appendChild (node to add): Add a node to the end of the child node list of the specified parent node

    var ul = document.querySelector('ul');
    ul.appendChild(li)
    

    node.insertBefore(child, specified element): Add a node to the front of the specified child node of the parent node

    var li = document. createElement('li');
    li.innerHTML = 'I will add it to the second child element of ul'
    ul.insertBefore(li, ul.children[1]);
    


    element.insertAdjacentHTML(position, text):
    The insertAdjacentHTML() method parses the specified text into an Element element and inserts the resulting node into the DOM tree at the specified position. it will not reparse the element it is using

    position: Indicates the position of the inserted content relative to the element, and must be one of the following strings
    beforebegin: before the element itself
    afterbegin: Insert before the first child node inside the element.
    beforeend: Insert after the last child node inside the element.
    afterend: Behind the element itself.

    <!-- beforebegin -->
    <p>
      <!-- afterbegin -->
      foo
      <!-- beforeend -->
    </p>
    <!-- afterend -->
    

    text: A DOMString to be parsed as an HTML or XML element and inserted into the DOM tree

    // Was <div id="one">one</div>
    var d1 = document. getElementById('one');
    d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');
    
    // At this point, the new structure becomes:
    // <div id="one">one</div><div id="two">two</div>
    

    delete node

    node.removeChild() removes a child node from the DOM, returns the removed node

    Clone Node

    node.cloneNode() Clone node node
    If the parenthesis parameter is empty or false, it is a shallow copy, that is, only the first layer of tags is copied without copying the content inside
    If the parenthesis parameter is true, it is a deep copy, which will copy the node itself and all its child nodes (including text nodes, etc.)

     <ul>
      <li>1 <a href="">test</a></li>
      <li>2</li>
    </ul>
    <script>
      var ul = document.querySelector('ul');
      var li = ul.children[0].cloneNode(true);
      ul.appendChild(li);
      var li2 = ul.children[0].cloneNode()
      ul.appendChild(li2)
    </script>
    

    The effect is as follows, only the li tag is cloned during shallow copying:

    replace node

    parentNode.replaceChild(newChild, oldChild), replace a child node of the current node with the specified node, and return the replaced node.

    Comprehensive case of node operation

    Make a simple post message case

    <body>
    <textarea name="" id=""></textarea>
    <button>Publish</button>
    <ul></ul>
    <script>
      // 1. Get the element
      var btn = document. querySelector('button');
      var text = document. querySelector('textarea');
      var ul = document. querySelector('ul')
      // add node function
      function add(value) {
        let li = document. createElement('li');
        console. log(value);
       li.innerHTML = `${value}<a href="#">delete</a>`;
        ul.prepend(li);
      }
    
      btn.onclick = function () {
        let value = text. value;
        if (!value) {
          alert('Published content cannot be empty');
          return;
        }
        add(value)
         text.value = '';
        text. focus();
        let deletValue = document. querySelectorAll('a');
        let cloneValue = document. querySelectorAll('. clone');
        //delete operation
        for (let i = 0; i < deletValue. length; i++) {
          deleteValue[i].onclick = function () {
           this. parentNode. remove();
          };
        }
      };
    </script>
    


    4. Event related content

    onclick

    Registered events are unique: only one handler function can be set for the same event on the same element, and the last registered function is the main one
    Remove event: eventTarget.onclick = null

    addEventListener()

    eventTarget. addEventListener(type, listener[, useCapture])

    type: event type string, such as click, blur, etc.
    listener: event processing function, the listening function will be called when the event occurs
    useCapture: optional parameter, is a boolean value. If it is true, it means that the event handler function is called during the event capture phase (from outside to inside); if it is false (default false), it means that the event handler function is called during the event bubbling phase (from inside to outside).
    Remove event: eventTarget.removeEventListener(type, listener[, useCapture]);


    Event Object

    e.target: The object (element) that triggers the event is returned, such as which element is clicked to return which
    this: What is returned is the object (element) that is bound to the event, such as which element is bound to the click event, which one is returned
    Click on the li of ul:

    var ul = document. querySelector('ul');
         ul. addEventListener('click', function(e) {
                 console.log(this); // ul is bound to events, so this points to ul
                 console.log(e.currentTarget);//Supports bubbling by default, pointing to the parent element ul of target
                 console.log(e.target);//Click on li, so e.target points to li
             })
    

    Prevent default behavior (event):
    If you use the addEventListener method: e.preventDefault()
    If you use onckick and other methods: return false Stop event bubbling: e.stopPropagation()


    Event delegation

    Principle: Add a listener to the parent node, and use event bubbling to affect each child node For example, register the click event for ul, and then use e.target to find the currently clicked li
    Effect: Only one DOM is operated, which improves the performance of the program

    ul.addEventListener('click',function(e){
    e.target.style.color = 'red'
    })
    


    Mouse Events

    e.client: The x and y coordinates of the mouse in the visible area. The returned value is relative to the coordinates of the visible area of the screen. If the page has scroll bars, the part hidden by the scroll bars will not be calculated
    e.page: The x and y coordinates of the mouse on the page document, the upper left corner of the document is (0,0), the right is positive, and the downward is positive
    e.screen: The x and y coordinates of the mouse on the computer screen
    e.offset returns the position of the element from the nearest parent element with positioning. If there is no positioning parent element, it is the body
    Note: The above four methods return all values ​​without units


    Keyboard events

    keypress : Triggered when a key is pressed, does not recognize function keys such as ctrl shift left and right arrows (the official website description of this event has been deprecated)

    WARNING: Since this event is deprecated, you should use beforeinput or keydown instead

    keydown : Triggered when the key is pressed and can recognize the function key
    keyup: Triggered when the key is up
    Note: onkeydown and onkeyup are not case sensitive
    KeyboardEvent.keyCode: The returned ASCII code value, which can be used to determine which key the user pressed (this function is no longer recommended, you should use KeyboardEvent.code)
    KeyboardEvent.code: This attribute represents the physical key on the keyboard, and returns a value that will not be changed by the keyboard layout or modifier key state. To determine the key character of the keyboard being pressed, the KeyboardEvent.key attribute is required. Here Method is case sensitive(This property is useful when you want to get the keys of the keyboard based on their physical position on the input device, especially common for game input in a gamepad-like environment)

    document.addEventListener('keydown', function(e) {
            console.log(e.key);
            console.log(e.code);
        })
    

    The effect is shown in the figure, and the output is the physical position of the button:

    Case: After pressing the s key to focus on the search box, press the Enter key to search for the function (the ASCII code value of the Enter key is 13, and the ASCII code value of the s key is 83):

    <input type="search">
     <script>
         var search = document. querySelector('input');
         document. addEventListener('keyup', function(e) {
             // Use the e.keyCode method
             // if(e.keyCode === 83){
             // search. focus()
             // }
             // if (e.keyCode === 13) {
             // window.location.href = `https://www.baidu.com/s?&wd=${search.value}`
    
             // }
    
             //Use the KeyboardEvent.code method
             if(e.code === 'KeyS'){
             //e.code is used here because s has uppercase and lowercase characters, and they are all in the same place KeyS, which can also be written as e.key === 'S'||e.key ==='s'
                 search. focus()
             }
             if (e.key==='Enter') {
             //The e.key is used here because the Enter key is Enter, but the position is different, it can also be written as e.code === 'Enter'||e.code === 'NumpadEnter'
                window.location.href = `https://www.google.com/search?&q=${search.value}`            
             }
         })
     </script>
    

    Popular posts from this blog

    大学资料分享——广工计院各个科目实验报告、课设及期末复习资料!!

    Win10 远程计算机或设备将不接受连接

    JAVA Traffic Signal Light Course Design (Source Code + Report + Video Demonstration)

    Implementation of Ajax Interceptor