目录

1. 获取 DOM 节点
2. DOM 节点的 property
3. DOM 节点的 attribute
4. attribute 和 property

1. 获取 DOM 节点

  1. getElementById
  2. getElementByClassName
  3. getElementByTagName
  4. querySeletorAll

2. DOM 节点的 property

通过 js 对象属性的方式来获取或修改 DOM 节点

js
const pList = document.querySelectorAll('p') const p = pList[0] console.log(p.style.width) // 获取样式 p.style.width = '100px' // 修改样式 console.log(p.className) // 获取 class p.className = 'p1' // 修改 class // 获取 nodeName 和 nodeType console.log(p.nodeName) console.log(p.nodeType)

3. DOM 节点的 attribute

通过 getAttribute setAttribute 这种 API 的方式来修改 DOM 节点

js
const pList = document.querySelectorAll('p') const p = pList[0] p.setAttribute('data-name', 'coder') // 设置值 console.log(p.getAttribute('data-name')) // 获取值

4. attributeproperty

  1. property:修改对象属性,不会体现到 html 结构中
  2. attribuite:修改 html 属性,会改变 html 结构
  3. 两者都有可能引起 DOM 重新渲染

propertyattribute 形式都可以修改节点的属性,但是对于新增或删除的自定义属性,能在 htmldom 树结构上体现出来的,就必须要用到 attribute 形式了。

如果对你有用的话,可以打赏哦
打赏
ali pay
wechat pay

本文作者:叶继伟

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!