class Dom {
  static css(el, css) {
    for (let key in css) {
      let k = key.replace(/([A-Z])/g, '-$1').toLowerCase()
      el.style[k] = css[key]
    }
  }

  static createElement(tagName, className, parentNode) {
    let el = document.createElement(tagName)
    if (className) {
      el.className = className
    }
    if (parentNode) {
      parentNode.appendChild(el)
    }
    return el
  }

  static insertAfter(newEl, targetEl) {
    var parentEl = targetEl.parentNode
    parentEl.insertAfter(newEl, targetEl)
  }

  static insertBefore(newEl, targetEl) {
    var parentEl = targetEl.parentNode
    parentEl.insertBefore(newEl, targetEl)
  }

  static removeClass(el, name) {
    let classes = el.className.trim().split(' ')
    let index = classes.findIndex(c => c === name)
    if (index !== -1) {
      classes.splice(index, 1)
    }
    el.className = classes.join(' ')
  }

  static addClass(el, name) {
    let classes = el.className.trim().split(' ')
    classes.push(name)
    el.className = classes.join(' ')
  }

  static parent(el, className) {
    // 查找el的父元素
    let parentNode = el.parentNode
    if (!parentNode || parentNode.tagName === 'BODY') {
      return null
    }
    if (parentNode.className.indexOf(className) !== -1) {
      return parentNode
    } else {
      return this.parent(parentNode, className)
    }
  }
}
export default Dom
