Node类型

NodeList

在JavaScript中,所有节点类型都继承Node类型

每个节点都有一个childNodes属性,其中包含一个NodeList的实例,
NodeList是一个类数组对象,用于存储可以按位置存取的有序节点
无论使用[],还是item() 都是可以的,但大多数开发者倾向于使用中括号,因为它是一个类数组对象
使用Array.prototype.slice(),可以把NodeList对象转化为数组

  1. let node = document.getElementById('app')
  2. console.log(node.childNodes)
  3. let first = node.childNodes[0]
  4. let second = node.childNodes[1]
  5. let secondChild = node.childNodes.item(1);
  6. let count = node.childNodes.length
  7. console.log(first, second, secondChild, count)

Document

document是JavaScript中表示文档节点的类型
在浏览器中,document是HTMLDocument的实例 (HTMLDocument继承Document)
nodeType: 9
nodeName: #document

  1. let html = document.documentElement
  2. console.log(html)
  3. let body = document.body
  4. // getElementById() getElementsByTagName()
  5. let div = document.getElementsByTagName('span')
  6. console.log(div, Array.from(div))

Element

nodeType: 1
nodeName: #标签名

  1. let div = document.getElementsByTagName('div')[0]
  2. console.log(div.className, div.id)

操作属性
getAttribute()
setAttribute()
removeAttribute()
创建元素
document.createElement()

Text

Selectors API

Selectors API Level 1
querySelector() 收CSS选择符参数,返回匹配该模式的第一个后代元素
querySelectorAll()返回所有匹配的节点,而不止一个。这个方法返回的是一个NodeList的静态实例。

  1. const el = document.querySelector('.app span')

html5

getElementsByClassName()