DOM

文档对象模型 (DOM) 是HTML和XML文档的编程接口。它给文档(结构树)提供了一个结构化的表述并且定义了一种方式—程序可以对结构树进行访问,以改变文档的结构,样式和内容。

document.location

location属性返回一个只读对象,提供了当前文档的URL信息

// 假定当前网址为http://user:passwd@www.example.com:4097/path/a.html?x=111#part1

document.location.href // "http://user:passwd@www.example.com:4097/path/a.html?x=111#part1"
document.location.protocol // "http:"
document.location.host // "www.example.com:4097"
document.location.hostname // "www.example.com"
document.location.port // "4097"
document.location.pathname // "/path/a.html"
document.location.search // "?x=111"
document.location.hash // "#part1"
document.location.user // "user"
document.location.password // "passed"

// 跳转到另一个网址
document.location.assign('http://www.google.com')
// 优先从服务器重新加载
document.location.reload(true)
// 优先从本地缓存重新加载(默认值)
document.location.reload(false)
// 跳转到另一个网址,但当前文档不保留在history对象中,
// 即无法用后退按钮,回到当前文档
document.location.assign('http://www.google.com')
// 将location对象转为字符串,等价于document.location.href
document.location.toString()

document.open()、document.close()

Element

除了document对象,在DOM中最常用的就是Element对象了,Element对象表示HTML元素。

Element 对象可以拥有类型为元素节点、文本节点、注释节点的子节点,DOM提供了一系列的方法可以进行元素的增、删、改、查操作

nodeName:元素标签名,还有个类似的tagName
nodeType:元素类型
className:类名
id:元素id
children:子元素列表(HTMLCollection)
childNodes:子元素列表(NodeList)
firstChild:第一个子元素
lastChild:最后一个子元素
nextSibling:下一个兄弟元素
previousSibling:上一个兄弟元素
parentNode、parentElement:父元素

createDocumentFragment()
createDocumentFragment方法生成一个DocumentFragment对象。

var docFragment = document.createDocumentFragment();
DocumentFragment对象是一个存在于内存的DOM片段,但是不属于当前文档,常常用来生成较复杂的DOM结构,然后插入当前文档。这样做的好处在于,因为DocumentFragment不属于当前文档,对它的任何改动,都不会引发网页的重新渲染,比直接修改当前文档的DOM有更好的性能表现。

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

推荐阅读更多精彩内容

  •   DOM(文档对象模型)是针对 HTML 和 XML 文档的一个 API(应用程序编程接口)。   DOM 描绘...
    霜天晓阅读 3,704评论 0 7
  • 前言:尽管现在有很多优秀的框架,大大简化了我们的DOM操作,但是我们仍然要学好DOM知识来写原生JS,从根本上去理...
    长鲸向南阅读 1,927评论 0 0
  • 什么是DOM D(document)O(object)M(model) 文档对象模型。 MDN的解释:DOM(文档...
    lyp82nkl阅读 444评论 0 0
  •   DOM 1 级主要定义的是 HTML 和 XML 文档的底层结构。   DOM2 和 DOM3 级则在这个结构...
    霜天晓阅读 1,483评论 1 3
  • 概述: DOM 是 JavaScript 操作网页的接口,全称为“文档对象模型”(Document Object ...
    阿尔托莉鸭阅读 1,102评论 1 31