javascript基礎系列:DOM相關的技術知識點 javascript基礎系列:DOM相關的技術知識點

javascript基礎系列:DOM相關的技術知識點

DOM及其基礎操作

DOM: document object model 文檔對象模型,提供一些屬性和方法供我們操作頁面中的元素

獲取DOM元素的方法

  1. document.getElementById() 指定在文檔中,基於元素的ID或者這個元素對象
  2. [context].getElementsByTagName() 在指定上下文(容器)中,通過標籤名獲取一組元素集合
  3. [context].getElementsByClassName() 在指定上下文中,通過樣式類名獲取一組元素集合(不兼容ie6-8)
  4. [context].getElementsByName() 在整個文檔中,通過標籤的name屬性值獲取一組元素集合(在ie中只有表單元素的name才能識別,所以一般只用於表單元素的處理)
  5. document.head/ document.body/docuementElement獲取頁面中的head/body/html元素
  6. [context].querySelector([selector]) (不兼容ie6-8)在指定的上下文中,通過選擇器獲取指定的元素對象
  7. [context].querySelectorAll([selector]) (不兼容ie6-8) 在指定的上下文中,通過選擇器獲取指定的元素集合

js中的節點和描述節點之間關係的屬性

  1. 節點:Node(頁面中所有的東西都是節點)
  2. 節點集合: NodeList(getElementsByName/querySelectorAll獲取的都是節點集合)
  • 元素節點(元素標籤)

nodeType: 1
nodeName: 大寫的標籤名
nodeValue: null

  • 文本節點

nodeType: 3
nodeName: '#text'
nodeValue: 文本內容

  • 註釋節點

nodeType: 8
nodeName: '#comment'
nodeValue: null

  • 文檔節點document

nodeType: 9
nodeName: '#document'
nodeValue: null

  1. 描述節點之間的關係的屬性
  • childNodes: 獲取所有的子節點(非ie6-8)中會把空格和換行當做文本節點
  • children: 獲取所有的元素子節點(子元素標籤)(ie6-8下會把註釋也當元素節點)
  • firstChild:獲取第一個子節點
  • lastChild: 獲取最後一個子節點
  • firstElemeentChild/lastElementChild(不兼容ie6-8)
  • previousSibling: 獲取上一個哥哥的節點
  • nextSibling: 獲取下一個弟弟節點
  • previousElementSibling/nextElementSibling: 獲取兄弟元素節點(不兼容ie6-8)
/**
    * children: 獲取指定上下文中,所有元素子節點
  * @params
  * context [element object]指定的上下文元素信息
  * @return
  *  [array] 返回所有的元素子節點集合
**/

function children(context) {
  // 1. 先獲取所有的子節點
    var res = [],
      nodeList = context.childNodes
  // 2. 循環遍歷所有的子節點,找出元素子節點,存儲到res中即可
  for(var i = 0; i < nodeList.length; i++) {
    var item = nodeList[i];
    item.nodeType === 1? res.push(item) : null
  }
  return res
}

// 獲取上一個哥哥元素
function prev(context) {
    var pre = context.previousSibling;
  while(pre.nodeType !== 1) {
    pre = context.previousSibling;
  }
  return pre;
}

在js中動態增刪改元素

  1. createElement 創建元素對象
  2. createTextNode 創建文本對象
  3. appendChild 把元素添加到容器的末尾
  4. insertBefore 把元素添加到指定容器元素的前面
// 動態創建一個div元素對象,把其賦給box
let box = document.createElement('div');
box.id = 'box'
box.style.width = '200px'
box.style.height = '200px'
box.className = 'red'
let text = document.createTextNode('珠峯培訓');

// 添加: 容器.appendChild(元素)
box.appendChild(text)
document.body.appendchild(box)

// 放到指定元素前: 容器.insertBefore([新增元素],[指定元素])
  1. cloneNode(true) 克隆元素或者節點
  2. removeChild 移除容器中的某個元素

設置自定義屬性的其它方式

setAttribute/getAttribute/removeAttribute 設置/獲取/刪除屬性

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章