DOM操作

1. DOM节点操作

DOM(Document Object Model)

1.1 prototype

property只是一个JS对象的属性的修改

// 新增节点
var div1 = document.getElementById('div1')
//添加新节点
var p1 = document.createElement('p')
p.innerHTML = 'this is p1'
div1.appendChild(p1) //添加新创建的元素
//移动已有节点
var p2 = document.getElementById('p2')
div1.appendChild(p2)
// 获取父元素和子元素
var div1 = document.getElementById( 'div1')
var parent = div.parentElement
var child = div.childNodes
div.removeChild(child[0])
// 删除节点
var div1 = document.getElementById( 'div1')
var child = div1.childNodes
div.removeChild(child[0])

1.2 attribute

Attribute是对html标签属性的修改

var pList = document.querySelectorAll('p')
var p = pList[0]
getAttribute('data-name')
setAttribute('data-name','imooc')
p.getAttribute('style')
p.setAttribute('style', 'font-size:30px;')

2. location

location.protocol // "http:"
location.host // "coding.m.imooc.com'
location.pathname // "/classindex. html"
location.search // "?cid=99"
location.search // "?cid=99&a=b"
location.hash // "#mid=100'
location.href // "http://coding.m.imooc com/class"

3. 事件绑定

3.1 通用事件绑定

var btn = document.getElementById('btn1')
btn.addEventListener('click', function (event) {
  console. log('clicked')
})

function bindEvent (elem, type, fn) {
  elem. addEventListener(type, fn)
}
var a = document.getElementById('link1')
bindEvent(a, 'click', function(e) {
  e.preventDefault() // 组织默认行为
  alert( 'clicked')
})

3.2 代理

var div1 = document.getElementById("div1")
div1.addEventListener('click', function (e) {
  var target = e.target
  if (target.nodeName === 'A') {
    alert(target.innerHTML)
  }
})

3.3 完善通用绑定事件的函数

function bindEvent(elem, type, selector, fn) {
  if (fn == null) {
    fn = selector
    selector = null
  }
  elem.addEventListener(type, function (e) {
    var target
    if (selector) {
      // 代理
      target = e.target
      if (target.matches(selector)) {
        fn.call(target, e)
      }
    } else {
      fn(e)
    }
  }
})

bindEvent (div1, 'click' , 'a', function () {})
bindEvent (div1, 'click' ,function () {})

你可能感兴趣的:(DOM操作)