DOM

What is the DOM

DOM (Document Object Model) is a standard programming interface recommended by W3C to deal with extensible Markup language. These interfaces allow you to change the content, structure, and style of a web page.

The DOM tree

  • Documentation: A page is a document
  • Element: All the tags in a page
  • Node: Everything in a web page is a node (tag, attribute, text, comment, etc.) represented in the DOM by Node

DOM treats all of these things as objects

Getting page elements

Gets the page element by ID

  1. Use the getElementById() method to get an element object with an ID.

    • Element is an Element object. Returns NULL if an element with a specific ID does not exist in the current document.
    • Id is a case-sensitive string that represents the unique ID of the element you are looking for.
    • It returns an element object

Usage:

<div id="id1">20000</div>
Copy the code
console.log(document.getElementById('id1'));//<div id="id1">20000</div>
// console.dir prints the element object we return to better view the properties and methods in it
console.dir(id1);
Copy the code

Gets page elements based on tags

  1. The getElementByTagName() method retrieves a collection of element objects based on the tag, stored as a pseudo-array (indexed, length) that returns an empty pseudo-array if no element exists on the page
var lis = document.getElementByTagName('li');
console.log(lis);  // Get all li tags
//lis[0] is the first li element
Copy the code
  1. Using element. GetElementsByTagName (‘ tag name), to obtain under the specified elements of child elements
var ol = document.getElementById('ol');
console.log(ol.getElementsByTagName(' li'));

Copy the code

Returns a collection of element objects based on the class name

Document. GetElementsByClassName (‘ the name of the class ‘);

querySelector

QuerySelector returns the first element object of the specified selector (only the first if multiple elements have the same class name)

Note: the class name is preceded by ‘. ‘and the id is preceded by’ # ‘.

var box = document.querySelector('.box ');
var nav = document.querySelector('#nav');
Copy the code

QuerySelectorAll () returns a collection of all element objects (pseudo-arrays) for the specified selector

var allBox = document.querySelectorAll( '.box ');  // Return all elements of class box
console.log(allBox);
var lis = document.querySelectorAl1( 'li');// Return all elements of the label li
console.log(lis);
Copy the code

Get special elements

//1. Get the body element
var bodyEle = document.body;
console.log(bodyEle);

console.dir(bodyEle);// Get all the contents and methods of the element

//2. Get the HTML element
var htmlEle = document.documentElement;
console.log(htmlEle);
Copy the code

The event

<button id="btn">Tong pak fu</button>
Copy the code

1. An event is composed of three parts: event source, event type, and event handler

We also call it the event triad

(1) The event source event is triggered by the object who buttons it

var btn = document.getElementById( ' btn' );
Copy the code

(2) How does the event type trigger what events such as mouse click (onclick) or mouse pass or keyboard press

(3) The event handler is done through a function assignment

btn.onclick = function() {}Copy the code
  1. Events can be added to any element of the document
  2. Common mouse events

Change element content (does not apply to forms, forms are modified by value)

<button>Displays the current system time</button>
<div>A certain time</div>
Copy the code
  1. Element. The innerText non-standard
    1. Does not recognize HTML tags
    2. Remove white space and line feeds at the beginning and end of text
    3. Read/write
var btn = document.querySelector('button');
var div = document.querySelector('div');
btn.onclick = function() {
    div.innerText = '123';
    div.innerText = '<strong>123</strong>';
}
console.log(div);//123, does not recognize HTML tags
console.log(div.innerText);//123, does not recognize HTML tags
Copy the code
  1. Element. The innerHTML w3c standard
    1. Identifying HTML tags
    2. Whitespace and line feeds at the beginning and end of the text are not removed
    3. Read/write
btn.onclick = function() {
    div.innerHTML = '123';
    div.innerHTML = '<strong>123</strong>';  // Display bold 123 in the page, identify the HTML tag
}
console.log(div.innerHTML);/ / 123, read/write

Copy the code

Change the content of a form element

var btn = document.querySelector(" button ");
var input = document.querySelector("input");
btn.onclick = function () {
  input.innerHTML = "Clicked"; // This does not work, this is a normal box such as the contents of the div tag
  // The value text in the form is modified by value
  input.value = "Clicked"; // The content is changed to click
};
Copy the code

Manipulate element values to modify style attributes

Style property operations

We can change the size, color, position and other styles of elements with JS.

  1. Element.style (inline style manipulation)
/ / 1. Access to elements
var div = document.querySelector("div");
/ / 2. Register event handlers
div.onclick = function () {
  // Change the background color
  this.style.backgroundColor = "purple";
};
Copy the code
  1. Element. className className style operation
.box{ color: #333; background-color: pink; margin-top:100px; }

<div>123</div>
Copy the code
var div = document.querySelector("div");
div.onclick = function () {
  this.className = "box"; // Click to make the div class box
};
Copy the code

Note:

  1. JS styles adopt camel naming methods such as fontSize and backgroundColor
  2. JS modify the style operation, resulting in inline style, CSS weight is relatively high
  3. ClassName directly changes the element’s className, overwriting the original className. (This. className = ‘old new’) (this.className = ‘old new’) (this.className = ‘old new’)

Gets the value of the property

Get property values

  • Element attributes.
  • Element. The getAttribute (‘ property ‘);

Element. attribute Gets the value of the built-in attribute (the element’s own attribute) element.getAttribute(‘ attribute ‘); Mainly get custom properties (standard) we programmers custom properties

<div id="demo" index="1"></div>; //index is a custom var div = document.querySelector("div"); // 1. Gets the element's attribute value /Console. log(div. Id); /(1)element. //demo
//(2)element.getAttribute(' attribute ')get Get the attribute value console.log(div.getAttribute("id")); //demo
console.log(div.getAttribute("index")); // 1Copy the code

Setting property values

<div id="demo" index="1"></div>; //index is a custom var div = document.querySelector("div"); // 1. Gets the element's attribute value /Div. Id = "demo2"; /(1)element. div.setAttribute("index", 2); div.setAttribute("class", "footer"); //class, in particular, it says class instead of classNameCopy the code

Remove the attribute element.removeAttribute(‘ attribute ‘);

div.removeAttribute("index");
Copy the code

Custom attributes

Custom attributes can only be 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 adds a new custom attribute: 1. Set H5 custom attribute H5 specifies a custom attribute data- as the attribute name and assign the value. Such as

2. Element. dataset. Index or Element. dataset[‘index’] IE 11

div.setAttribute( 'data-time'.20);
console.log(div.getAttribute('data-index')); / h5 New method to get custom attributes// Dataset is a collection containing all the custom attributes starting with data
console.log(div.dataset);
I
console.log(div.dataset.index);

// If there is an attribute with two - components such as:
console.log(div.getAttribute( 'data-list-name'));
// We should remove the - and use the small hump nomenclature
console.log(div.dataset['listName']);

Copy the code

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

In general, a node has at least nodeType (nodeType), nodeName (nodeName), and nodeValue

Basic attributes:

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)

The node operations we use in real development mainly operate on element nodes

The parent node parentNode

<div class="box">
  <span class="erweima">x</span>
</div>
Copy the code
var erweima = document.querySelector(".erweima");
console.log(erweima.parentNode); //<div class="box"><span class="erweima" >x</span></div>
Copy the code

Returns null if there is no parent node

Child nodes

1. node.childNodes

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 the following specialized processing. So childNodes is generally not recommended

var ul = document.querySelector("ul");
for (var i = o; i < ul.childNodes.length; i++) {
  if (ul.childNodes[i].nodeType == 1) {
    // ul.childNodes[I] is the element node
    console.log(ul.childNodes[i]); }}Copy the code

2. Parentnode. children(non-standard)

Parentnode. children is a read-only property that returns all child element nodes and is a pseudo-element. 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

3. First child node

parentNode.firstChild

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

4. Last child node

parentNode.lastChild

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

5. parentNode.firstElementChild

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

6. parentNode.lastElementChild

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

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

The actual developed script has no compatibility issues and returns the first child

console.log(ol.children[0]);
console.log(ol.children[ol.children.length - 1]);
Copy the code

Brother nodes

1. Element.nextsibling returns the nextSibling (including the text node), or null if not found

<div>I am a div</div>
<span>I am a span</span>
<script>
  var div = document.querySelector("div");
  // nextSibling the nextSibling contains element nodes, text nodes, etc
  console.log(div.nextSibling);
</script>
Copy the code

2. Element. previous Sibling Returns the previous Sibling (including the text node), if not found, returns null

NextElementSibling gets the next sibling node

4. PreviousElementSibling Get the last sibling node

These two methods can get element nodes, but there are compatibility problems, to solve the element nodes and compatibility problems can be solved by encapsulation function

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

Add and delete nodes

  1. CreateElement Creates the node element.appendChild Appends the node to the end of the parent element
<ul></ul>
<script>
  / / 1. Create a node element node
  var li1 = document.createElement("li");
  var li2 = document.createElement("li");
  / / 2. Node. appendChild(Child) Node parent Child is the child and is the appended element
  var ul = document.querySelector("ul");
  ul.appendChild(li1);
  / / 3. InsertBefore (child) A node's parent child appends an element to the specified element
  ul.insertBeforeChild(li2, ul.children[0]);
</script>
Copy the code
  1. element.insertAdjacentHTML(position,text); Position is the position of the relative element and is one of the following strings:
    • ‘beforeBegin’ precedes the element itself
    • ‘afterBEGIN’ is inserted before the first node inside the element
    • ‘beforeend’ inserts after the first node inside the element
    • After the ‘afterend’ element itself
<ul>
  <li></li>
  <li></li>
  <li></li>
</ul>
<script>
  var ul = document.querySelector("ul");
  var li = '<li class="a">123</>'
 ul.insertAdjacentHTML('beforeend',li);
  • 123
  • </script> Copy the code

    Text is the HTML or XML to be parsed and inserted into the DOM tree

    1. Remove node node.removechild (child)
    <ul>
      <li></li>
      <li></li>
      <li></li>
    </ul>
    <script>
      var ul = document.querySelector("ul");
      ul.removeChild(ul.children[0]);
    </script>// node.removechild (child) Where node must be the parent of the node to be removed, child is the node to be removedCopy the code
    Blocking link hops

    javascript:;

    <a href="javascript:;"></a
    ><! The link does not jump -->
    Copy the code

    Clone node

    Node. The cloneNode (), copy the node

    The node.clonenode () method returns a copy of the node on which it was called. Also known as clone node/copy node

    Note: 1. If the parenthesis parameter is blank or false, it is a shallow copy, that is, only the replicated node itself is cloned, not the child nodes inside it. ⒉. If the parenthesis argument is true, it is a deep copy, which copies the node itself and all its children.

    var ul = document.querySelector("ul");
    // 1. node.cloneNode(); If parentheses are empty or false is inside, shallow copy copies only tags but not contents l/
    node.cloneNode(true); // The parentheses are true. The deep copy copy tag copies the contents inside
    
    var lili = ul.children[0].cloneNode(true); / / copy ul. Children [0]
    ul.appendChild(lili);
    Copy the code
    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, which writes content to a DOM node, does not cause the page to be completely redrawn
    3. InnerHTML is more efficient at creating multiple elements (concatenating strings is less efficient, concatenating arrays is more efficient) and has a slightly more complex structure
    4. CreateElement () creates multiple elements slightly less efficiently, but with a cleaner structure

    DOM focus core

    With respect to DOM manipulation, we focus on manipulation of elements. There are mainly create, add, delete, change, check, attribute operation, event operation.

    1. create
    • document.write
    • innerHTML3. createElement
    1. increase
    • appendChild
    • insertBefore
    1. delete
    • removeChild
    1. The modification mainly modifies dom element attributes, CONTENT and attributes of DOM elements, and form values, etc
    • Modify element attributes: SRC, href, title, etc
    • Modify the innerHTML and innerText of a normal element
    • Modify form elements: Value, Type, disabled, etc
    • Modify the element styles: style, className
    1. The query mainly gets the element of the DOM query
    • API methods provided by DOM: getElementById, getElementsByTagName Older usage is not recommended
    • H5 provides new methods :querySelector, querySelectorAll advocate
    • Use node operation to get elements: parentNode, children, previousElementSibling. NextElementSibling advocacy
    1. Property operations are focused on custom properties.
    • SetAttribute: Sets the DOM attribute value
    • GetAttribute: Gets the DOM attribute value
    • RemoveAttribute Removes an attribute
    1. Event operations register events for elements, taking event sources. Event type = event handler

    There are two ways to register events

    1. The Registration event overview adds events to elements, called registration events or binding events.

    There are two ways to register events: traditional and method listening registration

    Traditional Registration

    Use the onclick event starting with on.

    <button onclick="alert('hi~')"></button>
    <script>
      btn.onclick = function () {};
    </script>
    Copy the code
    • Features: Uniqueness of registered events
    • Only one handler can be set for an element and an event. The last one registered will override the previous one

    Method listens for the registration mode

    W3c standard recommendations

    AddEventListener () is a method

    Internet Explorer prior to Internet Explorer 9 does not support this method. Instead, use attachEvent() instead

    Features: Multiple listeners can be registered for the same element and event in the order in which they are registered

    var btns = document.querySelectorAll("button"); / / 1. Register events the traditional way
    btns[0].onclick = function () {
      alert("hi");
    };
    
    btns[0].onclick = function () {
      alert("hao a u");
    };
    / / 2. Event listener Register event addEventListener
    // The event type inside (1) is the string must be quoted without on
    // (2) Add more listeners to the same element and event
    btns[1].addEventListener("click ".function () {
      alert(22);
    });
    
    btns[1].addEventListener("click".function () {
      alert(33);
    });
    
    btns[2].addEventListener("click ", fn); // Fn inside does not need to be called with parentheses
    
    function fn() {
      alert(44);
    }
    // Click BTNS [1] to pop up 22, then 33
    Copy the code

    Delete event (unbind event)

    1. Eventtarget. onclick =null;
    2. Method listens for the registration mode
    • EventTarget. RemoveEventListener (type, the listener, useCapture []);
    • eventTarget.detachEvent (eventNameWithOn,callback);
    var divs = document.querySelectorAll("div");
    divs[0].onclick = function () {
      alert(11);
      / / 1. Divs [0]. Onclick = null;
    };
    // 2. RemoveEventListener Deletes the event
    divs[1].addEventListener("click", fn); // Fn inside does not need to be called with parentheses
    function fn() {
      alert(22);
      divs[1].removeEventListener(" click", fn);
    }
    / / 3.
    divs[2].attachEvent("onclick", fn1);
    function fn1() {
      alert(33);
      divs[2].detachEvent("onclick ", fn1);
    }
    Copy the code

    Flow of events

    The event flow describes the order in which events are received from the page. When events occur, they are propagated in a specific order between element nodes, which is called the DOM event stream.

    For example, we registered click events for a div: the DOM event flow is divided into three phases

    • Capture phase
    • Current target stage
    • Bubbling phase

    Event bubbling: a process first proposed by IE in which an event is initially received by the most specific element and then propagated up the hierarchy to the topmost node of the DOM.

    Event capture: first described by Netscape, the process of starting with the topmost node of the DOM and propagating down the hierarchy to the most specific element received.

    When events occur, they are propagated in a specific order between element nodes, which is called the DOM event stream.

    Pay attention to

    1. Only one of these phases can be captured or bubbled in Js code.
    2. Onclick and attachEvent only get the bubbling phase.
    3. AddEventListener (type, listener[,useCapture]) the third argument, if true, calls the event handler during the event capture phase; If false(the default is false), the event handler is invoked during the event bubbling phase.
    4. We rarely use event capture in real development, focusing more on event bubbling.
    5. Some events do not bubble, such as onblur, onFocus, onMouseerker, onmouseleave
    6. Event bubbling can sometimes cause trouble, and sometimes it can help to do something very subtly, as we’ll explain later.

    Event capture

    When an element and its parent are both bound to the same event, for example:

    <div class='father'>
       <div class = 'son'>
    
       </div>
    </div>
    
    <script>
       var son = document.querySelector('.son');
       var father = document.querySelector('.father');
       son.addEventListener('click'.function(){
          alert('son');
       }.true)
        father.addEventListener('click'.function(){
          alert('father');
       }.true)
    </>
    Copy the code

    This is done from the outside in the order of capture. When son is clicked, father pops up and then Son pops up

    The event bubbling

    When an element and its parent are both bound to the same event, for example:

    <div class="father">
      <div class="son"></div>
    </div>
    
    <script>
      var son = document.querySelector(".son");
      var father = document.querySelector(".father");
      son.addEventListener(
        "click".function () {
          alert("son");
        }.false
      );
      father.addEventListener(
        "click".function () {
          alert("father");
        }.false
      );
    </script>
    Copy the code

    This is done from the inside out in the order of capture. When son is clicked, son pops up first and then father pops up

    The event object

    1. What is an event object
    eventTarget.onclick = function (event) {};
    eventTarget.addEventListener("click ".function (event) {});
    // The event is the event object, which we prefer to write as e or evt
    Copy the code

    The event object represents the state of the event, such as the state of the keyboard key, the position of the mouse, and the state of the mouse button.

    After an event occurs, a collection of information data related to the event is put into this object. This object is the event object, which has many properties and methods.

    Such as:

    1. Who bound this event.
    2. When the mouse triggers an event, it gets information about the mouse, such as its position.
    3. When the keyboard triggers an event, it gets information about the keyboard, such as which key was pressed.
    • The event is a parameter that the system sets for us as an event object without passing an argument.

    • When we register an event, the event object is automatically created by the system and passed in turn to the event listener (event handler).

    • The event object can be named by ourselves such as Event. evt and e

    • The event object have compatibility problems ie678 through the window. The event compatibility of writing e = e | window. The event;

    Common properties and methods for event objects

    // 1.e.target returns the object that triggered the event. This returns the object to which the event was bound.
    // Difference :e.target clicks on that element, returns that element this is bound to the click event, returns who
    var div = document.querySelector("div ");
    div.addEventListener("click ".function (e) {
      console.log(e.target);
      console.log(this);
      // When the div has no child elements, both console. logs print out the div element
    });
    var ul = document.querySelector("ul"); / / under ul li
    ul.addEventListener(" click ".function (e) {
      // we bind the event to ul so this points to ul
      console.log(this); // Either click ul or click li under ul returns ul
      // e.target points to the object we clicked on who triggered the event we clicked on Li
      console.log(e.target); // Click ul to return the element li. Click ul to return the element ul
    });
    Copy the code

    The event object blocks the default behavior

    // Prevent default actions (events) such as not redirecting links or not submitting buttons
    var a = document.querySelector("a");
    a.addEventListener("click".function (e) {
      e.preventDefault(); //dom standard
    });
    / / 3. Traditional registration methods
    a.onclick = function (e) {
      // common browser e.preventdefault (); methods
      e.preventDefault();
      // Lower version Browser IE678 returnValue property
      e.returnValue;
      // We can use return false to prevent default behavior without compatibility problems: the code after return is not executed and is limited to traditional registration methods
      return false;
      alert(11);
    };
    Copy the code

    Stop Event bubble Propagation()

    Prevent events from bubbling only at that level

    <div class="father">
      <div class="son"></div>
    </div>
    
    <script>
      var son = document.querySelector(".son");
      var father = document.querySelector(".father");
      son.addEventListener(
        "click".function (e) {
          e.stopPropagation(); // Prevent events from bubbling
          alert("son");
        }.false
      );
      father.addEventListener(
        "click".function (e) {
          alert("father");
        }.false
      );
    </script>
    Copy the code

    Event delegation

    Event delegates are also called event proxies, or event delegates in jQuery.

    How event delegation works:

    Instead of setting event listeners individually for each child node, event listeners are set on its parent node and then influence each child node to be set using the bubbling principle.

    For example: register a click event for UL, then use the target of the event object to find the current hit li, because the event will bubble up to UL, ul has a registration event, which will trigger the event listener.

    Function of event delegate:

    We only manipulated the DOM once, improving the performance of the program.

    Common mouse event objects

    Common Keyboard events

    Priorities of the three events: Up == Down == press

    Keyboard event object

    Keyboard event object properties instructions
    keyCode Returns the ASCII value of the key

    The event type when retrieving keyCode: onKeyDown and onKeyUp are case insensitive, onKeyPress is case sensitive. In our actual development, we use keyDown and KeyUp more, which recognizes all keys (including function keys).

    Keypress does not recognize function keys, but the keyCode attribute is case sensitive and returns different ASCII values

    document.addEventListener('keyup'.function(e) {
       console.log( ' up: ' + e.keycode);
       // We can use the ASCII value returned by keycode to determine which key the user pressed
       if (e.keyCode === 65) {
          alert('The A key you pressed');
       }else{alert) You did not press the A key'); }})Copy the code