This is the 10th day of my participation in the August More text Challenge. For details, see: August More Text Challenge.

preface

About the SSD series: Some interesting content on the front end, aimed at 3-10 minutes, 500-1500 words, gain without being burdened.

First a wave of questions :(without a frame)

  • What are the common methods of querying nodes

  • What is a blank node? What the hell is she

  • QuerySelectorAll for pits

  • How do I query pseudo-elements

  • Do you know all four ways to delete a node

  • HTMLCollection and NodeList difference

  • How to delete all child nodes

We already have the advantages of jquery, Vue, React, etc.

  • Let’s not talk about jquery. One$Walk the world, infinite.
  • Vue and ReactrefI get the corresponding node.

Can you operate a 666 Node without these frameworks?

In this paper, the source code

crud-doms

Nodes in the query

Let’s put in a little bit of HTML code for the test

  <div class="outer" id="outer">
    <ul class="list list-1">
      <li class="item">list-one</li>
      <li class="item">list-two</li>
      <li class="item">list-three</li>
    </ul>
  </div>

  <input type="button" name="btnSubmit" value="Refresh"/>
Copy the code

Common node query methods

  1. getElementById

    A node query is performed based on the value of the element’s ID attribute, returning a single node.

    document.getElementById("outer")  // <div class="outer" id="outer">......
    Copy the code
  2. getElementsByClassName

    Query based on the classname attribute value of the element.

    document.getElementsByClassName("item") // HTMLCollection(3) [li.item, li.item, li.item]
    Copy the code
  3. getElementsByName

    To query the name attribute of the root node.

    document.getElementsByName("btnSubmit") // NodeList [input]
    Copy the code
  4. getElementsByTagName

    Query by node label name.

    document.getElementsByTagName("li") // HTMLCollection(3) [li.item, li.item, li.item]
    Copy the code
  5. querySelector

    Root out the CSS selector to query a node and return a single node.

    document.querySelector("#outer") // <div class="outer" id="outer">......
    Copy the code
  6. querySelectorAll

    Root out the CSS selector to query nodes and return the node list.

    document.querySelectorAll(".item") // NodeList(3) [li.item, li.item, li.item]
    Copy the code

    Before the appearance of querySelector and querySelectorAll, methods are basically extended by the first four query methods combined with childNodes and parentNode methods.

Some special query properties

  • Document. all returns all nodes
  • Document. images Returns all images
  • Document. forms returns all forms
  • Document.links returns all the link tags
  • Document. embeds returns allobjectTag elements, previously used mainly for Flash, PDF, etc

QuerySelectorAll Note

  • It returns a static NodeList, and subsequent changes to the DOM elements do not affect the contents of its collection.

    As you can see from the code below, the nodeList length does not change after adding a section.

      <ul class="list list-1">
        <li class="item">list-one</li>
        <li class="item">list-two</li>
        <li class="item">list-three</li>
      </ul>
    
      <script>
          var  nodeList = document.querySelectorAll(".item");
          console.log(Len: "", nodeList.length);  / / 3
    
          var liEl = document.createElement("li");
          liEl.className = "item";
          liEl.innerHTML = "list-for"
          document.querySelector(".list").appendChild(liEl);
          
          console.log(Len: "", nodeList.length); / / 3
      </script>
    Copy the code
  • QuerySelectorAll may not return the value you expect

    <div class="outer">
      <div class="select">
        <div class="inner">
        </div>
      </div>
    </div>
    
    <script>
    var select = document.querySelector('.select');
    var inner = select.querySelectorAll('.outer .inner');
    inner.length; // 1, not 0!
    </script>
    
    Copy the code

    So how do you return the desired result? The answer is: the scope

    var select = document.querySelector('.select');
    var inner = select.querySelectorAll(':scope .outer .inner');
    inner.length; / / 0
    Copy the code
  • Escape special characters

      <div id="foo\bar"></div>
      <div id="foo:bar"></div>
    
      <script>
        console.log('#foo\bar')               // "#fooar"
        document.querySelector('#foo\bar')    // Does not match any elements
    
        console.log('#foo\\bar')              // "#foo\bar"
        console.log('#foo\\\\bar')            // "#foo\\bar"
        document.querySelector('#foo\\\\bar') // Match the first div
    
        document.querySelector('#foo:bar')    // Does not match any elements
        document.querySelector('#foo\\:bar')  // Match the second div
      </script>
    Copy the code

HTMLCollection and NodeList difference

A careful note may have noticed that some of the above methods return HTMLCollection, while others return NodeList. What’s the difference?

Here’s where inheritance gets clear:

HTMLElement -> Element -> Node-> EventTarget
Copy the code

EventTarget provides event distribution capabilities and is also a subscription publisher. For more details, see 3 lines of code: a subscription publisher.

There are 12 types of Node. For details, see NodeType. We often use div, span and other Node types whose NodeType is 1.

So:

HTMLCollection is an element nodeType, that is, a node with nodeType 1.

A NodeList is a collection of nodes, including text nodes, comment nodes, and so on.

How do I query pseudo-elements

/ / HTML code<style>
    .nihao::before{
      content: 'Hello,';
    }
  </style>
  <div class="nihao" id="nihao">
    Tom
  </div>
Copy the code

The answer is no, but you can get the style by using window.getComputedStyle.

window.getComputedStyle(nihao, "before")["content"]// "hello, \""Copy the code

The node to delete

Let me first highlight the HTML snippet of the test

  <ul class="list list-1">
    <li class="item">list-one</li>
    <li class="item">list-two</li>
    <li class="item">list-three</li>
  </ul> 
Copy the code

Node.removeNode

This method is most commonly used when you first obtain the parentNode of the element to be deleted. You can obtain this using either parentNode or parentElement.


    var ul = document.querySelector(".list");
    console.log("li length", ul.children.length);  / / 3
    ul.removeChild(ul.children[0])  // removeChild
    console.log("li length", ul.children.length); / / 2

Copy the code

Element.remove

This method belongs to the Element object, which means that other nodeType types are not available and do not need to acquire secondary nodes.


    var ul = document.querySelector(".list");
    console.log("li length", ul.children.length);  / / 3
    ul.children[0].remove();  // remove
    console.log("li length", ul.children.length); / / 2

Copy the code

Or outerHTML innerHTML


   var ul = document.querySelector(".list");
    console.log("li length", ul.children.length);  / / 3
    ul.children[0].outerHTML = null   // outerHTML
    console.log("li length", ul.children.length); / / 2


Copy the code

Document.adoptNode

Get a node from another Document document. This node and all nodes in its subtree are deleted from the original document.


var ul = document.querySelector(".list");
console.log("li length", ul.children.length);  / / 3
document.adoptNode(ul.children[0]); // adoptNode
console.log("li length", ul.children.length); / / 2

Copy the code

Deleting Nodes in Batches

Batch deletations, such as clearing all the children of a node, are usually done using a while loop. The violent method is innerHTML = null.

The innerHTML = null may cause the event listener to not be canceled, resulting in a memory leak, depending on the browser implementation.

Let’s encapsulate one:

function clearChildNodes(node){
    while(node.hasChildNodes()){ node.removeChild(node.firstChild); }}const ul = document.querySelector(".list");
console.log("nodes:", ul.childNodes.length);  / / 7
clearChildNodes(ul);   
console.log("nodes:", ul.childNodes.length);  / / 0
Copy the code

Blank nodes

Why seven nodes? Look at the blank nodes on the picture. There are four of them. 4+3 =7 floors.

Let’s adjust the code, remove the white space, and look at the output

  <ul class="list list-1"><li class="item">list-one</li><li class="item">list-two</li><li class="item">list-three</li></ul>
Copy the code

What the hell is that blank node?

Look at the code, it is actually a text node with nodeType 3. TextConent is empty when output.

   var ul = document.querySelector(".list");
    console.log("li length", ul.childNodes.length);  / / 7

    var firstNode = ul.childNodes[0];
    console.log("nodeType", firstNode.nodeType);  / / 3
    console.log("content", firstNode.textContent); // 
Copy the code

Let’s add a little bit of content and you can see clearly that the childNodes length is still 7 and the first text node is the text content

  <ul class="list list-1">text content
    <li class="item">list-one</li>
    <li class="item">list-two</li>
    <li class="item">list-three</li>
  </ul> 
Copy the code

summary

Is not very simple, everything looks not so difficult, so, you can easily into the pit ah.

Length takes precedence, and if the star exceeds 100, write another article with node additions and updates.

Write in the last

Writing is not easy, your praise and comments are the biggest motivation for me to move forward. Technical exchange group, please add wechat dirge-cloud.

Node

HTMLElement

querySelectorAll