In the days of frames, how many of you remember how we controlled dom behavior without frames? The author himself neglected to learn this until the interview question came up and he decided to get to know the DOM API better.

Node, Document, and Element

All three are confusing when learning the DOM API. Sort out their relationship.

node

Node is an interface from which things like Document and Element inherit. This interface provides access to and manipulation of DOM nodes. There are many types of node, some of which are listed below. It can be seen from the figure that the type code of Element is 1, the type code of text node is 3, the type code of annotation node is 8, and the type code of document is 9.


node type

This reminds me of the code that appears multiple times in vue.js: if (child.nodeType === 3) {… } is used to determine whether the current node is a text node.

element

An element is a special node (nodeType == 1). An element is an HTML tag that carries special attributes, such as <p><div>. So Element can use all of Node’s apis.

document

Similarly, document is a special node that differs from Element in that it is usually a DOM node, a node that contains the head and body elements.

Difference between Node object and Element object? – Stack Overflow

API learning

First of all, I noticed that all DOM operations start with the use of document to retrieve various types of Nodes (collections) and then perform various DOM operations! Because the DOCUMENT operation API is really a lot, so I choose the part I want to learn. The purpose of my DOM API study here is to:

Learn how document objects operate dom, have the ability to operate DOM outside the framework (jquery, Vue, etc.).

Access to the node

  • Document.documentElement Returns the immediate descendant of Document.
  • Document.activeelement Returns the element currently being manipulated
  • Document.bodyOf the current document<body>Elements. Similarly, the document. head and document. scripts properties return the current Document<head><script>Elements.
  • Document. GetElementByClassName () returns a list of elements which have given the style name
  • Document. The getElementByTagName () returns with the elements of a given tag name list
  • Document.getelementbyid () returns an object reference to the identified element
  • Document.queryselector () returns the first element in the document that matches the specified selector
  • Document. QuerySelectorAll () returns a match selector specified element node list
  • Node.childNodesReturns a real-time view that contains all the children of the nodeNodeList“Real-time” means that if the children of that node change,NodeListThe object is automatically updated.
  • FirstChild & node.lastchild returns the first or lastChild of the Node, or null if the Node has no children.
  • Node.previousSibling & node. nextSibling returns the last or nextSibling at the same level as the Node, or null if not.
  • Node.ownerDocumentReturns the value to which this element belongsDocumentObject.
  • Node.parentNodeReturns a current nodeNodeParent node of.
  • Node.parentElementReturns a parent of the current nodeElement.

Operation node

  • Document.createcomment () creates a new comment node and returns it
  • Document. CreateDocumentFragment () to create a new Document fragments
  • Document.createelement () creates a new element with the given tag name.
  • Document.createtextnode () creates a literal node
  • Document.write() writes to the Document (document.writeln () has a similar function except that it is followed by a newline character).
  • Element.innerHTML Sets or returns the content of the Element
  • Node.textcontent gets or sets the textContent of all children of a tag and their descendants.
  • Node.appendchild () adds a new child Node to the element as the last child.
  • Node.clonenode () clones the element (passed deep or deep if true).
  • Node.insertBefore()Inserts a new node before specifying an existing node (noneinsertAfterMethods. You can useinsertBeforeMethods andnextSiblingTo simulate it.)
  • Node.normalize() merges adjacent text nodes in elements
  • Node.removechild () removes child nodes from an element
  • Node.replacechild () replaces the child nodes in the element

The Document createXXX method has some other not commonly used, if you need to use it, please refer to MDN.

Other common properties and methods

  • Element.classList returns the class collection of elements.
  • EventTaget. AddEventListener () registered to monitor events
  • Node.nodeType Returns the type code of the Node
  • Node.nodeValue Returns or sets the value of the current Node.
  • Node.com pareDocumentPosition () to compare the current node with arbitrary relationship between the location of another node in the document.
  • Node. Contains () whether the Node passed is a descendant of the Node.
  • Node.haschildnodes () whether it hasChildNodes
  • Node.isequalnode () checks whether two elements are equal
  • Node.issamenode () checks whether two elements are the same Node

The above contents refer to the contents on MDN:

  • The Node developer.mozilla.org/zh-CN/docs/…
  • Element developer.mozilla.org/zh-CN/docs/…
  • The Document developer.mozilla.org/zh-CN/docs/…

Write an example of manipulating the DOM

Now you use these apis to do some DOM manipulation.

Gets nodes at various locations.

Here’s a little demo:

<div id="container"> <div> <h1>get dom</h1> <ul id="list"> <li><span>hello world 1</span></li> <li><span>hello world 2</span></li> <li><span>hello world 3</span></li> <li><span>hello world 4</span></li> <li><span>hello world 5</span></li> </ul> </div> <br/> <div> <button>commit</button> </div> </div> <script> var container = Document.getelementbyid ('container') console.log(' List all nodes ', Container..childnodes) var h1 = document. GetElementsByTagName (' h1) [0] console. The log (' after obtain h1 elements, h1.nextSibling) var uldiv = container.firstChild while (uldiv && uldiv.nodeType ! = 1) { uldiv = uldiv.nextSibling } var ul = uldiv.lastChild while (ul && ul.nodeType == 3) { ul = ul.previousSibling } Console. log(' get the content of the first element in ul ', ul.firstchild) var doc = h1.ownerDocument console.log(' Get the current Document object ', Doc) var li1 = ul.firstChild console.log(' get li's parent ', li1.parentElement) var button = document.getElementsByTagName("button")[0] button.onclick = log button.focus() Button.click () console.log(' Get the element being manipulated ', document.activeElement) function log(){ console.log('button is clicked') } </script>Copy the code

The final result is shown as follows:


Returns the result



nodeType == 1


Practice creating, inserting, and deleting nodes.

<div> <div id="container"> <h2 id="child">Hello Child</h2> </div> <br/> <div id="buttonGroup"></div> </div> <script> // Function appendChild(){var container = document.getelementById ("container") var text = Document.createelement ("h2") text.textContent = 'Hello New Child' container.appendChild(text)} Function appendParent(){var child = document.getelementById ('child') var parent = child.parentelement var text = document.createElement("h1") text.textContent = 'Hello Parent' var root = parent.parentElement root.insertBefore(text, Function appendPre(){var child = document.getelementById ('child') var text = document.createElement("h2") text.textContent = 'Hello Pre Child' child.parentElement.insertBefore(text, Function appendNext(){var child = document.getelementById ('child') var text = document.createElement("h2") text.textContent = 'Hello Next Child' child.parentElement.insertBefore(text, Function removeEle(){var container = document.getelementById ('container') if (container.lastChild) {container.removechild (container.lastChild)}} function replaceEle(){var child = document.getElementById("child") var newNode = document.createElement('div') newNode.innerHTML = "<button>button</button>hello new node replaced" var parent = child.parentElement parent.replaceChild(newNode, Var ButtonGroup = document.getelementById (" ButtonGroup ") var EventList = ["appendChild", "appendParent", "appendPre", "appendNext", "removeEle", "replaceEle" ] var ButtonArr = [] for (var key of EventList) { var btn = document.createElement('button') btn.textContent = key btn.onclick = eval(key) ButtonArr.push(btn) } for (var b of ButtonArr) { ButtonGroup.appendChild(b) } </script>Copy the code

The above code implements inserting elements at various locations and removing and replacing elements.

Simple implementation of V-for, V-text, V-HTML, V-ON and V-Model functions.

Well, as a vue.js fan, it’s hard to get around the idea of vue.js manipulating the DOM. This is a simple implementation (no Virtual DOM involved, just pure DOM modification). If you are not familiar with the Vue commands, you can check out their usage on the official website.

<html>
    <head>
        <meta charset="UTF-8">
        <title>Hello Ele</title>
    </head>
    <body>
        <div id="container">
            <h1>v-text</h1>
            <span>{{ message }}</span>
            <h1>v-html</h1>  
            <div v-html="messagespan"></div>          
            <h1>v-model</h1>
            <input v-model="message"/>
            <h1>v-on</h1>
            <input id="myInput" v-on:blur="blur" v-on:focus="focus"/>
            <h1>v-for</h1>
            <ul></ul>
        </div>
        
        <script>
            // v-text
            var message = "Hello World"
            var messagespan = "<span>Hello World</span>"
          
            var spans = document.getElementsByTagName("span")
            for (var span of spans) {
                if (span.textContent == "{{ message }}") {
                    span.textContent = message
                }
            }
            // v-html
            var container = document.getElementById("container")
            var divs = container.getElementsByTagName("div")
            for(var div of divs){
                if (div.getAttribute("v-html") == "messagespan") {
                    div.innerHTML = messagespan
                }
            }
            // v-model
            var inputs = container.getElementsByTagName("input")
            for (var input of inputs) {
                if (input.getAttribute("v-model") == "message") {
                    input.setAttribute("value", message)
                }
            }
            // v-on
            var myInput = document.getElementById("myInput")
            myInput.onfocus = eval(myInput.getAttribute("v-on:focus"))
            myInput.onblur = eval(myInput.getAttribute("v-on:blur"))

            function focus(){
                myInput.setAttribute("value", "focus")
            }

            function blur() {
                myInput.setAttribute("value", "blur")
            }
            // v-for
            var liContents = [
                "jack",
                "rose",
                "james",
                "wade",
                "jordan"
            ]

            var liElementList = []
            for(var content of liContents) {
                var li = document.createElement("li")
                li.innerHTML = `<label><input type="checkbox"/><span>${content}</span></label>`
                liElementList.push(li)
            }
            var ul = container.getElementsByTagName("ul")[0]
            for (var liEle of liElementList) {
                ul.appendChild(liEle)
            }
        </script>
    </body>
</html>
Copy the code

The final result is shown as follows:




According to the results

Simple implementation of the vue. js command these functions, in fact, vue. js source code is also used to do the DOM operation API. More Vue source DOM operations can see my “Vue. Js source code learning six – VNode virtual DOM learning” in this article.

The last

No matter what the framework is, in fact, all changes are inseparable from its root. In the end, it’s all functionality implemented with the most basic API. So it is very important to learn the basic knowledge ~ PS: MDN is reliable, although w3School has a lot of information, but I feel not very reliable… Later to check information as far as possible to MDN English website to check (Chinese website translation some problems).