[JS Interaction] Basics of DOM Operation

1. Overview of DOM

insert image description here

1.1 What is DOM

  • DOM (Document Object Model) document object model, the basic API used to represent and manipulate the content of html or xml documents;
  • When a web page is loaded, the browser creates the document object model DOM of the page, and the DOM model is constructed as a tree of objects (Dom Html Tree);
  • DOM contains all html tag elements, text strings, and even html comments;
  • Using the properties and methods in the DOM, the program has the ability to dynamically access and update the content, structure and style of the document, which greatly enhances the interactivity of the page;

Native JavaScipt Case Collection
JavaScript + DOM Basic
JavaScript Basic to Advanced
Canvas Game Development

1.2 DOM application

  • All HTML elements in the page can be changed through DOM manipulation;
  • All HTML attributes in the page can be changed through DOM manipulation;
  • All CSS styles on the page can be changed through DOM manipulation;
  • Can respond to all events in the page through DOM operations;

1.3 DOM tree

DOM calls each object in the hierarchy a node. This hierarchy can be regarded as a tree structure, just like our directory. There are subdirectories under a root directory, and subdirectories under the subdirectory. The DOM tree diagram is as follows;

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-rCxjW8vT-1691456155382)(01_DOM foundation.assets/image-20210220113047306.png)]

1.4 DOM node types and related attributes

All objects in the DOM tree are nodes, such as: document nodes, element nodes, attribute nodes, text nodes, comment nodes, etc.;

Node-related attributes are as follows:

  • nodeName Get the name of the node, read-only
  • nodeValue get node content (for text nodes and comment nodes)
  • nodeType get node type, read only

There are different node types for files, elements, attributes, etc. of an HTML or XML document. There are 12 different node types, and different node types can also have different child node types as follows:

node type describe child node
1 Element an element Element, Text, Comment, ProcessingInstruction, CDATASection, Entity Reference Manual
2 Attr a property Text, Entity Reference Manual
3 Text The textual content or attributes of an element None
4 CDATASection CDATA section of a document None
5 Entity Reference Manual entity reference Element, ProcessingInstruction, Comment, Text, CDATASection, Entity Reference Manual
6 Entity an entity Element, ProcessingInstruction, Comment, Text, CDATASection, Entity Reference Manual
7 ProcessingInstruction a processing instruction None
8 Comment a note None
9 Document The entire document (the root node of the DOM tree) Element, ProcessingInstruction, Comment, DocumentType
10 DocumentType Provides an interface for document entities None
11 DocumentFragment Represents adjacent nodes and their subtrees. Element, ProcessingInstruction, Comment, Text, CDATASection, Entity Reference Manual
12 Notation Represents the declaration of a symbol in the DTD None

The node type can be judged by the attribute nodeType, so the DOM tree can be divided into the following two types according to the node type:

  • The first is the DOM tree mentioned above, which contains all types of tags, attributes, text, comments, etc., which can be called a node tree;
  • The second is a type that only contains tags, which can be called an element tree. The element tree diagram is more concise, and it is faster to search and operate. Therefore, unless necessary, the element tree is generally used for operations.

1.5 DOM Node Hierarchy

The so-called node relationship in the DOM tree is similar to our human direct relationship, which is nothing more than father-son relationship, brother relationship, and grandparent relationship; the corresponding nodes are as follows:

  • Parent node (parent node) A parent node can have any number of child nodes
  • Child node (child node) A child node can only have one parent node
  • sibling node (sibling node) has the same parent node sibling node
  • Root node (root node) An html document generally has only one root node. The root node has no parent node and is the top node.
  • Ancestor nodes All nodes that contain child nodes can be called ancestor nodes, including parent nodes
  • Descendant nodes All nodes contained in a node are called descendant nodes, including child nodes

1.6 Hierarchical access to nodes

  • parentNode Get the parent node of the current node
  • childNodes Get all child nodes of the current element node
  • firstChild Gets the first child node of the current element node
  • lastChild Gets the last child node of the current element node
  • previousSibling Gets the previous sibling node of the current node
  • nextSibling Get the next sibling node of the current node

1.7 Hierarchical access to elements (access between Element element nodes)

  • firstElementChild, lastElementChild are similar to firstChild and lastChild, and the return type is only Element type, ignoring text, comments, and blank nodes (IE8 and below return undefined)
  • nextElementSibling and previousElementSibling are similar to nextSibling and previousSibling, and the return type is only Element type, ignoring text, comments, and blank nodes (IE8 and below return undefined)
  • children Get the collection of all child elements of the current element
  • childElementCount the number of child elements
  • Element can also access the parentNode property, but the returned results are all of type Elment

1.8 Introduction to document object properties

  • document.documentElement Get the root node of the document
  • document.body Get the body object of the document
  • document.cookie set and get cookie (local storage later)
  • document.readyState Get the loading state of the current document

Two, DOM basic operation

2.1 Six ways to get elements

  • getElementById() Get elements by id name
  • getElementsByTagName() Get elements by tag name
  • getElementsByClassName() Get elements by class name
  • getElementsByName() Gets elements by the value of name, which is generally used in forms (labels with name attributes)
  • querySelector() Gets the first element that meets the criteria through the css selector
  • querySelectorAll() Gets all elements that meet the criteria through the css selector

2.2 Ways to output content to the page

  • document.write()
  • element.innerHTML
  • element.innerText

2.3 Attributes and methods for manipulating html attributes

  • Set and get element attributes through object attributes, format element.att || element[att] such as: img.src li.type div.className div.id p.style etc.
  • Set and get attributes (all html attributes) via get/set methods
    • element.getAttribute(name) Get the value of the attribute through the attribute name of the element node
    • element.setAttribute(name,value) set the attribute value in the element
    • element.removeAttribute(name) delete the specified attribute

2.4 Get and set css style

  • internal style

    • Add styles by setting html attributes above

      p.style.color = "red";
      p.style = "color:red;text-indent:2em;";
      p.setAttribute("style","color:red;text-indent:2em;")
      
    • Use cssText to add multiple styles

      p.style.cssText = "color:red;text-indent:2em;";
      
    • clear internal styles

      element.style.cssText = "";
      element.removeAttribute("style","");
      element.style="";
      
  • External styles (consider compatibility)

    Advanced browsers use window.getComputed(element, null)

    IE lower version browsers use element.currentStyle

    // 浏览器兼容性写法
    function getOutStyle(ele,attr) {
        if (window.getComputedStyle) { //兼容高版本
            return window.getComputedStyle(ele)[attr];
        } else { //兼容 IE8以下
            return ele.currentStyle[attr];
        }
    }
    

Three, DOM advanced operation

3.1 Node Creation

  • createElement() creates an element node

  • createTextNode() creates a text node

  • createAttribute() creates attribute nodes, which are assigned by nodeValue or value

    Attribute nodes are set by means of the setAttributeNode(attr) method

  • createComment() creates a comment node

3.2 Node operation

  • appendChild() Appends a child element node to the specified element

  • insertBefore(newNode, oldNode) Insert a new child element node before the specified element inside the parent element

  • replaceChild(newNode, oldNode) replaces the original child node inside the parent element with a new node

  • cloneNode(deep?) clones the specified node, the parameter deep defaults to false, and only clones the current node. Set true to clone all current and descendant nodes

  • removeChild() removes the specified child element node from the parent element

  • remove(index?) remove the specified (index) node

    例: 删除下拉列表中选中的菜单项
    ================================== html代码 ================================
    <select id="mySelect">
    function removeOption(){
        <option>苹果</option>
        <option>香蕉</option>
        <option>葡萄</option>
        <option>西瓜</option>
        <option>橙子</option>
    </select>
    <input type="button" onclick="removeOption()" value="移除选中的菜单项"/>
    ================================== js代码 ================================
    function removeOption(){
        var myEle = document.getElementById("mySelect");
        myEle.remove(myEle.selectedIndex);
    }
    小贴士:selectedIndex 属性可设置或返回下拉列表中被选选项的索引号;若允许多重选择,则仅会返回第一个被选选项的索引号	
    

    element.removeAttributeNode(attributename) deletes the specified attribute node and returns the removed node

  • hasChildNodes() is used to check whether the current element has child nodes

Four, DOM operation case

Collection of native JavaScript cases

4.1 Tab switching

insert image description here

4.2 Comment system

insert image description here

4.3 Comments on Weibo

insert image description here

4.4 Shopping Cart

insert image description here

expand:

Both xml and json are used to store data, but the xml structure looks clear, while the json string structure is not easy to view; but xml is not concise enough, and for computers, json strings are more economical to store data.

Guess you like

Origin blog.csdn.net/qq_39335404/article/details/132159059