概述
document节点对象是文档的根节点,每张网页都有自己的document对象。
属性
1.document.doctype 获取doctype节点
var doctype=document.doctype
console.log(doctype)//< ! DOCTYPE html>
console.log(doctype.name)//html
2.document.documentElement 返回当前文档的根节点,一般是HTML
3.document.charset 返回当前文档的编码方式
4.document.title 返回当前文档的标题,可读可写
console.log(document.documentElement)
console.log(document.charset)
console.log(document.title)
5.document.body/ document.head 返回文档中的body和head节点
console.log(document.body)
console.log(document.head)
6.document.links 返回当前文档中所有的链接
<body>
<a href="http://www.baidu.com">1</a>
<a href="http://www.taobao.com">2</a>
</body>
<script>
var links=document.links;
for(var i=0 ; i<links.length;i++){
console.log(links[i])
}
</script>
7.document.forms 返回当前文档所有的Form表单节点
<body>
<form action="" ></form>
</body>
<script>
console.log(document.forms)
</script>
8.document.images返回页面所有的图片节点
<body>
<img src="" alt="" />
<img src="" alt="" />
<img src="" alt="" />
<img src="" alt="" />
</body>
<script>
console.log(document.images)
var img=document.images;
for(var i=0;i<img.length;i++){
console.log(img[i])
}
</script>
方法
1.document.createElement() 创建元素节点
var span=document.createElement("span")//创建元素节点
document.body.appendChild(span)
2.document.createTextNode() 创建文本节点
var txt=document.createTextNode("新的文本")//创建文本节点
span.appendChild(txt)
3.document.createComment() 创建一个注释节点
var com=document.createComment("注释节点")//创建注释节点
document.body.appendChild(com)
4.document.createAttribute() 创建属性节点
var attr=document.createAttribute("id")//创建属性节点
attr.value="attrVal"
span.setAttributeNode(attr)
// span.setAttribute('class','attrVal')