Lingquan | Blog

HTML DOM Key Concepts

Word count: 316Reading time: 1 min
2018/10/26 Share

classlist of dom node

1
2
3
4
5
6
7
function addClass(selector, className){
var elm = document.querySelector(selector);
if (elm){
elm.classList.add(className);
//elm.classList.remove(className);
}
}

innerHTML, innerText, textContent

1
<p id="test">    This element    contains <span>an inner span</span>. </p>
  • The values of these properties of the “test” paragraph will be:
  • innerText: “This element contains an inner span.” : Just the text, trimmed and space-collapsed.
  • innerHtml: “ This element contains an inner span. “ All spacing and inner element tags.
  • textContent: “ This element contains an inner span. “ Spacing, but no tags.

Repaint vs Reflow

  • reflow: flow of the elements in the page is changed due to change size or position
  • repaint: It happens when you change the look of an element without changing the size and shape. This doesn’t cause reflow as geometry of the element didn’t changed. eg, change visibility

CreateDocumentFragment

  • documentFragment a lightweight or minimal part of a DOM or a subtree of a DOM tree.
  • It is very helpful for improving performance when you are manipulating a part of DOM for multiple times.

Tranverse Dom tree

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 // 广度优先遍历
function bfs(root) {
let queue = [root];

while(queue.length) {
let curNode = queue.shift();
console.log(curNode);

if(!curNode.children.length) {
continue;
}

Array.from(curNode.children).map((child) => queue.push(child));

}
}

// 深度优先遍历
function dfs(root){
let child = root.firstElementChild;

while(child) {
console.log(child);
dfs(child);
child = child.nextElementSibling;
}
}

DOM API

  • addEventListener & removeEventListener

    1
    2
    3
    4
    5
    // Attach an event handler to the document
    document.addEventListener("mousemove", myFunction);

    // Remove the event handler from the document
    document.removeEventListener("mousemove", myFunction);
  • createAttribute() & setAttributeNode()

    1
    2
    3
    4
    5
    6
    function myFunction() {
    var h1 = document.getElementsByTagName("H1")[0];
    var att = document.createAttribute("class");
    att.value = "democlass";
    h1.setAttributeNode(att);
    }
  • createElement() & intersetBefore() & appendChild()

  • querySelector & querySelectorAll()
CATALOG
  1. 1. classlist of dom node
  2. 2. innerHTML, innerText, textContent
  3. 3. Repaint vs Reflow
  4. 4. CreateDocumentFragment
  5. 5. Tranverse Dom tree
    1. 5.1. DOM API