天天看點

DOM 操作寫法示例

選取元素

document.querySelector('a') // 傳回找到的第一個,不存在傳回 null
document.querySelectorAll('a') // 傳回所有,類型是 NodeList。不存在傳回長度為 0 的 NodeList           

複制

周遊元素

[].slice.call(document.querySelectorAll('a')).forEach(function(el, index){
  console.log( index + ": " + el.innerHTML );
})           

複制

建立元素

var newEl = document.createElement('div')           

複制

複制元素

el.cloneNode(true)           

複制

元素的末尾插入子元素

el.appendChild(newEl)           

複制

元素的開始插入子元素

el.insertBefore(newEl, el.firstChild)           

複制

目前元素前面插入元素

el.parentNode.insertBefore(newEl, el)           

複制

目前元素後面插入元素

el.parentNode.insertBefore(newEl, el.nextSibling)           

複制

删除元素

el.parentNode.removeChild(el)           

複制

判斷兩個元素是否相等

el === otherEl           

複制

表單元素

擷取/設定值

document.querySelector('#my-input').value // 擷取
document.querySelector('#my-input').value = 3 // 設定           

複制

單選/複選框選中狀态

document.querySelector('input[type=checkbox]').checked
document.querySelector('input[type=checkbox]').checked = true           

複制

内容

el.textContent
el.textContent = 'xxx'
el.innerHTML
el.innerHTML = 'xxx'           

複制

屬性

el.getAttribute('href')
el.setAttribute('href', 'xxx')
el.tagName           

複制

類名

el.classList.add(className)
el.classList.remove(className)
el.classList.contains(className) // hasClass           

複制

樣式

// 注意:此處為了解決當 style 值為 auto 時,傳回 auto 的問題
var win = el.ownerDocument.defaultView;
// null 的意思是不傳回僞類元素
win.getComputedStyle(el, null).color; // 擷取元素的顔色

el.style.color = '#ff0011'           

複制

尺寸

// 與 jQuery 一緻(一直為 content 區域的高度)
function getHeight(el) {
  const styles = this.getComputedStyle(el);
  const height = el.offsetHeight;
  const borderTopWidth = parseFloat(styles.borderTopWidth);
  const borderBottomWidth = parseFloat(styles.borderBottomWidth);
  const paddingTop = parseFloat(styles.paddingTop);
  const paddingBottom = parseFloat(styles.paddingBottom);
  return height - borderBottomWidth - borderTopWidth - paddingTop - paddingBottom;
}
// 精确到整數(border-box 時為 height 值,content-box 時為 height + padding + border 值)
el.clientHeight;
// 精确到小數(border-box 時為 height 值,content-box 時為 height + padding + border 值)
el.getBoundingClientRect().height;           

複制

事件

el.addEventListener('click', function(event){
  console.log(this.innerHTML)
})           

複制

參考

  • You Don't Need jQuery