DOM总结

简单整理一下dom操作,备忘。

查询元素

getElementById()
getElementsByClassName()
getElementsByTagName()
getElementsByName()
querySelector()
querySelectorAll()

创建元素

createElement()
createTextNode()
createDocumentFragment()

修改元素

appendChild()
insertBefore()
replaceChild()

删除元素

removeChild()

clone元素

cloneNode()

属性操作

div.id/className...
getAttribute()
createAttribute()
setAttribute()
removeAttribute()
element.attributes

其他:

innerText
innerHTML

常见使用方式

1.修改样式
可修改元素的 style 属性,修改结果直接反映到页面元素

document.querySelector('p').style.color = 'red'
document.querySelector('.box').style.backgroundColor = '#ccc'
2.获取样式 getComputedStyle
使用getComputedStyle获取元素计算后的样式,不要通过 node.style.属性 获取

var node = document.querySelector('p')
var color = window.getComputedStyle(node).color
console.log(color)

class 操作

var nodeBox = document.querySelector('.box')
console.log( nodeBox.classList )
nodeBox.classList.add('active') //新增 class
nodeBox.classList.remove('active') //删除 class
nodeBox.classList.toggle('active') //新增/删除切换
node.classList.contains('active') // 判断是否拥有 class

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 概要 64学时 3.5学分 章节安排 电子商务网站概况 HTML5+CSS3 JavaScript Node 电子...
    阿啊阿吖丁阅读 9,308评论 0 3
  • 对 DOM 的两个主要的扩展是 Selectors API(选择符 API)和HTML5,还有Element Tr...
    sunnyghx阅读 312评论 0 0
  • Element 除了document对象,在DOM中最常用的就是Element对象了,Element对象表示HTM...
    jrg_tzc阅读 170评论 0 0
  • 文档对象模型 (DOM) 是HTML和XML文档的编程接口。它给文档(结构树)提供了一个结构化的表述并且定义了一种...
    mhy_web阅读 420评论 0 0
  • 要开心 力所能及的事情要竭尽全力的去帮助别人 舔你爱的人 对过去的事不要一副苦瓜脸,对未来也不要愁眉苦脸 只要 活...
    莹萱阅读 357评论 0 0