DOM and BOM operations

Posted by jakep on Wed, 22 Dec 2021 14:55:24 +0100

DOM and Bom

DOMBOM
Document object modelBrowser object model
Treat the document as a * * * object***Treat the browser as a * * * object***
The top-level object of DOM is DocumentThe top-level object of BOM is window
DOM is mainly used to manipulate page elementsBOM s are objects that interact with browser windows
DOM is the W3C Standard SpecificationBOM is a child of browser manufacturers. The compatibility defined on their browsers is poor

Common window events:

Page load event
  • window.onload is a window (page) loading event. This event (including images, script files, CSS files, etc.) will be triggered when the document content is fully loaded, and the processing function will be called
 <button>Click the button</button>
    // Traditional writing
    <script>
        window.onload = function() {
            var btn = document.querySelector('button');
            btn.addEventListener('click', function() {
                alert("Click me");
            })
        }
        // The latest writing
        window.addEventListener('load', function() {
            var btn = document.querySelector('button');
            btn.addEventListener('click', function() {
                alert("Click me");
            })
        })
        // DOMContentLoaded
        document.addEventListener('DOMContentLoaded', function() {
            alert("DOMContentloaded event")
        })
    </script>

window.onload the traditional registration event method can only be written once. If there are multiple events, the last window will be used Onload shall prevail
When the DOMContentLoaded event is triggered, only when the DOM is loaded, excluding style sheets, pictures, flash, etc. (supported only for IE9 and above)
DOMContentLoaded is faster than the load method

Resize window event
  • window.onresize resizes the window to load events, and calls the function when triggered
<script>
        window, addEventListener('resize', function() {
            console.log("The window has changed");
        })
    </script>;

DOM

Create element node
  • createElement create element node
  • createTextNode creates a text node
  • After appendChild is added to an element
var oDiv = document.createElement("div"); //Create element node
        document.body.appendChild(oDiv);
        var oText = document.createTextNode("abc"); //Create a text node. / / put the created div into the body
        oDiv.appendChild(oText);
Get label element
  • getElementById() get by ID
var oBox = document.getElementById("box"); //Pass id
      console.log(oBox);
  • getElementsByTagName('div ') is obtained by tag name
 var aDivs = document.getElementsByTagName("div"); //By tag name
      console.log(aDivs); //Collection pseudo array (class array object)
  • getElementsByClassName gets the element by class name
 var aTests = document.getElementsByClassName("test"); //By class name
      console.log(aTests); //Collection pseudo array (class array object)
  • getElementsByName gets the element from the name value
 var aSps = document.getElementsByName("sp"); //By name value
      console.log(aSps); //Collection pseudo array (class array object)
  • querySelector gets the first element
 var oDiv = document.querySelector("div"); //Through the selector, you can only get the first item of the set
      console.log(oDiv);
  • querySelectorAll gets all elements of the element
 var aDivs = document.querySelectorAll("div");//Get all DOM objects corresponding to the selector
      console.log(aDivs);

case

  • document.body.replaceChild(); >>>>> Replace a node
  • document. body. removeChild(); >>>>> Delete a node
  • oDiv. appendChild(oCloneNode); >>>>> Clone a node
<body>
// Replace the div with id box with a P
<div id="box">div</div>
    <div class="test">div</div>
    <p class="test">duanluo</p>
    <span name="sp">span</span>
<script>
var oP = document.createElement("p");  //Get current label
var oDiv = document.getElementByid("box");
document.body.replaceChild(op,oDiv);  // Replace a node
</script>
</body>

Browser object

  • window.onscroll is triggered when the browser's scroll bar scrolls
  • window.onresize is triggered when the browser window size changes
window.onscroll Triggered when the browser's scroll bar scrolls
window.onscroll = function () {
  console.log("ok");
  }
   window.onresize = function () {
        console.log("ok");
      };
  • scrollTop vertical scroll bar scrolling distance
// Gets the number of pixels to scroll
var  intElemScrollTop = someElement.scrollTop;

After running this code, intElemScrollTop is an integer, that is, the number of pixels in which the content of element scrolls up.

  • scrollLeft horizontal scroll bar scrolling distance
//Gets the distance from the scroll bar to the left of the element
var sLeft = element.scrollLeft;

sLeft is an integer representing how many pixels the element scroll bar is to the left of the element.

//Sets how many pixels the scroll bar scrolls
element.scrollLeft = 10;

scrollLeft can be any integer:

  • If the element cannot be scrolled (for example, the element does not overflow), the value of scrollLeft is 0.
  • If the value set for scrollLeft is less than 0, the value of scrollLeft becomes 0.
  • If the value set for scrollLeft is greater than the maximum width of the element content, the value of scrollLeft will be set to the maximum width of the element.
  • Element. The width and height of the viewable area of the clientwidth / clientheight browser
var cw = document.documentElement.clientWidth;
var ch = document.documentElement.clientHeight;
console.log(cw, ch)
  • Element. The clientwidth property represents the internal width of the element in pixels. This attribute includes padding of the inner margin, but does not include border, margin of the outer margin, and vertical scroll bar
  1. This property is read-only. It is 0 for an element that does not define CSS or inline layout box. Otherwise, it is the internal height of the element (unit pixel), including the inner margin, but excluding the horizontal scroll bar, border and outer margin.

Get custom properties:

  • element. Property gets the property value.
  • element.getAttribute('attribute ');
difference:
  • element. Property to get the built-in attribute value (the attribute of the element itself)
  • element.getAttribute('attribute '); Mainly get custom attributes (standard) our programmers' custom attributes

Remove attribute:

  • element.removeAttribute('attribute ');

H5 custom attributes

  • H5 specifies that the beginning of the custom attribute data - is used as the attribute name and assigned a value.
  • Get compatibility element getAttribute(‘data-index’);
  • H5 new element dataset. Index or element Dataset ['index'] ie 11 started to support
// for example
<div data-index="1"></div>
// Or use JS settings
element.setAttribute('data-index', 2)

Node operation:

  1. Using DOM tree, nodes can be divided into different hierarchical relationships, commonly parent-child brother hierarchical relationships
node.parentNode  // The parent node of a node can be returned. If there is no parent node, null will be returned
  1. Child node
 parentNode.children(Non standard)//Is a read-only attribute that returns all child element nodes. It returns only child element nodes, and the rest are not returned
 parentNode.firstChild  // Returns the first child node, or null if it cannot be found. Similarly, it contains all nodes.
 parentNode.lastChild //Returns the last child node. If it cannot be found, it returns null. Similarly, it contains all nodes.
 parentNode.firstElementChild //Returns the first child element node, or null if it is not found.
 parentNode.lastElementChild  //Returns the last child element node. If it cannot be found, it returns null.
 // h5 new method for obtaining custom attributes
 div.dataset.index 
 div.dataset['index']
<div getTime="20" data-index="5" data-list-name="andy"></div>
    <script>
        var div = document.querySelector('div');
        console.log(div.getAttribute('getTime'));
        div.setAttribute('data-time', 20);
        console.log(div.getAttribute('data-index'));
        // H5 new method for obtaining custom attributes
        // dataset is a collection containing all custom attributes starting with data
        console.log(div.dataset);
        console.log(div.dataset.index);
        console.log(div.dataset['index']);
        // If there are multiple linked words in the custom attribute, hump naming shall be adopted when obtaining
        console.log(div,tataset['lisyName']);
    </script>

Node overview:

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

  • Element node nodeType is 1
  • The attribute node nodeType is 2
  • The text node nodeType is 3 (the text node contains text, spaces, line breaks, etc.)
    In the main development, the node operation mainly operates the element node

Child node operation:

  • Element.childNodes[0].nodeType; (not recommended)
  • Element. Children (recommended)
  • Element.children[0] compatible writing
  • Element.firstChild gets the first child element node
  • Element.lastChild gets the last child element node
  • Element.firstElementChild returns the first child element node. If it cannot be found, it returns null
  • Element.lastElementChild returns the last child element node. If it cannot be found, it returns null
  • Element.nextSibling is the next sibling node, including element nodes or text nodes
  • Element. The previous sibling node contains element nodes or text nodes
  • Element. Nextlementsibling returns the next sibling element node of the current element. If it cannot be found, it returns null
  • Element.previousElementSibling returns the previous sibling element node of the current element. If it cannot be found, it returns null
    <div class="box">
        <span class="erweima"></span>
        <span class="erweima"></span>
        <span class="erweima"></span>
    </div>
    <script>
        //Parent node parentNode
        var erweima = document.querySelector('.erweima');
        var box = document.querySelector('.box');
        console.log(erweima.parentNode); //Get the parent node closest to the element. If the parent node is not found, null will be returned
        //Child nodes all child nodes include element nodes, text nodes, and so on
        console.log(box.children);
    </script>

Create node:

  • Element.appendChild adds an element node after
  • Element.insertBefore adds the element node before
       <ul>
        <li>childOne</li>
    </ul>
    <script>
        // 1. Create node
        var lis = document.createElement('li');
        var oUl = document.querySelector('ul');
        // 2. Add node AppendChild (child) node parent child child
        oUl.appendChild(lis) //Add element after
            // 3. Add node InsertBefore (child, specify element)
        var childOne = document.createElement('li');
        oUl.insertBefore(childOne, oUl.children[0]);
    </script>

Delete node

  • Element.removeChild delete node
 <button>delete</button>
    <ul>
        <li>ONE</li>
        <li>TWO</li>
        <li>THREE</li>
    </ul>
    <script>
        var ul = document.querySelector('ul');
        var btn = document.querySelector('button');
        btn.onclick = function() {
            if (ul.children.length == 0) {
                this.disabled = true;
            } else {
                ul.removeChild(ul.children[0]);
            }
        }
    </script>

Clone node (replication node):

  • Element.cloneNode()

If the parenthesis parameter is empty or false, it is a shallow copy, that is, only the replicated node is cloned, and the child nodes inside are not cloned

  • Element.cloneNode(); If the bracket is true, it is a deep copy. Copy the label and copy the contents at the same time
  <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
    </ul>
    <script>
        //node.cloneNode();  If the bracket is empty or false, it is a shallow copy. Only the label is copied, and the content in it is not copied
        // node.cloneNode(); If the bracket is true, it is a deep copy. Copy the label and copy the contents at the same time
        var ul = document.querySelector('ul');
        var lis = ul.children[0].cloneNode(true);
        ul.appendChild(lis);
    </script>

Differences between three dynamic creation elements

  • document.write()
  • element.innerHTML
  • document.createElement()
difference
  1. document.write is the content stream that directly writes the content to the page, but when the document stream is completed, it will cause all pages to be redrawn
  2. innerHTML is to write the content to a DOM node, which will not cause all pages to be redrawn
  3. innerHTML is more efficient in creating multiple elements (don't splice strings, splice them in the form of arrays), and the structure is slightly complex
  4. innerHTML is more efficient in creating multiple elements (don't splice strings, splice them in the form of arrays), and the structure is slightly complex

innerHTML is more efficient than createElement in different browsers

  • To be added

Topics: Javascript BOM