文章目录
  1. 1. Nodes
  2. 2. Normal internal API/property
  3. 3. Node Type
  4. 4. Normal operation code
  5. 5. firstChild VS firstElementChild
  6. 6. Attr
  7. 7. Node 效率/资源相关
  8. 8. About classList
  9. 9. About Style
  10. 10. Less code with select
  11. 11. Reference

Nodes

node: DOM > HTML

Normal internal API/property

Property
firstChild
lastChild
childNodes
previousSibling
nextSibling
nodeType
attribute

Node Type

Property value
Node.ELEMENT_NODE 1
Node.TEXT_NODE 3
Node.COMMENT_NODE 7
Node.DOCUMENT_FRAGMENT_NODE 11

Normal operation code

Node大部分操作都是通过对子节点的操作API,也就是说必须获得parentNode

  • select:

    document.querySelector();
    Ele.querySelectorAll();

  • append:

    parentEle.appendChild(childEle);
    parentEle.insertBefore(newEle, referenceEle);

  • prepend:

    1
    2
    3
    function prependChild(newNode, parentNode) {
    parentNode.insertBefore(newNode, parentNode.firstChild);
    }
  • replace:

    parentNode.replaceChild(newChild, oldChild);

  • clone: 不带事件绑定

    Ele.cloneNode(true); // 带上子节点
    Ele.cloneNode(flase[default value]); // 仅复制自身节点

  • create:

    document.createElement(‘div’);
    document.createTextNode(‘text’);

  • delete:

    node.parentNode.removeChild(node);
    node.remove(); // IE not support

  • more with Node control: Link | MDN

firstChild VS firstElementChild

firstChild include other nodes like textNode. Refer #Node Type.

Attr

hasAttribute(attrName);
getAttribute(attrName);
setAttribute(attrName, value);
removeAttribute(attrName);

Node 效率/资源相关

  • 查询
    每个节点都有childNodes属性,,它保存了这个节点所有 直接 子元素

调用childNodes返回的是一个NodeList对象,它极其像数组,但是有一个最关键的地方,它是动态查询的,也就是说每次调用它都会对DOM结构查询,所以对它的使用需要慎重,注意性能

可利用 Node.hasChildNodes() Node.contains() 进行子节点查询

  • 批量创建node – with document.createDocumentFragment
    这个速度差别很大, 性能方面优先考虑
    #nodeType 中, 可以看到fragment node依然存在, 需要注意这个点

PS: the difference between innerText and textContent
the main diff performance:

About classList

Ele.classList.[]

  • add()
  • remove()
  • toggle(String[, condition]) condition: Boolean true/false
  • contains() return: Boolean true/false

About Style

  • get

    window.getComputedStyle(Ele[, pseudoEle]);

  • set

    Ele.style.xxx = ‘xxx’; // attention: camel style
    Ele.setAttr(‘style’, …);

Less code with select

Reference

通俗易懂的来讲讲DOM
JavaScript操作DOM的那些坑

文章目录
  1. 1. Nodes
  2. 2. Normal internal API/property
  3. 3. Node Type
  4. 4. Normal operation code
  5. 5. firstChild VS firstElementChild
  6. 6. Attr
  7. 7. Node 效率/资源相关
  8. 8. About classList
  9. 9. About Style
  10. 10. Less code with select
  11. 11. Reference