每个载入浏览器的 HTML 文档都会成为 Document 对象。
*: Document 对象是 Window 对象的一部分,可通过 window.document 属性对其进行访问
document 获取元素
document.getElementById(id) //通过id获取
document.getElementsByClassName(classname) //通过class获取 数组形式
document.getElementsByName(name) //通过标签中的name获取 数组形式
document.getElementsByTagName(tagname) //通过标签名称获取 数组形式
document.getElementsByTagNameNS(ns,name) //ns表示要查询的元素的命名空间名称,name表示要查询的元素的名称,其中特殊字符 "*" 代表所有元素
常用方法示例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="app" class="box"></div>
<div class="box"></div>
</body>
</html>
<script type="text/javascript">
var app = document.getElementById("app")
console.log("获取app")
console.log(app)
var box = document.getElementsByClassName("box")
console.log("获取box")
console.log(box)
</script>
还有一些其他的方法
document.open() //打开一个流,以收集来自任何 document.write() 或 document.writeln() 方法的输出。
document.close() //关闭用 document.open() 方法打开的输出流,并显示选定的数据。
document.write() // 向文档写 HTML 表达式 或 JavaScript 代码。
document.writeln() //等同于 write() 方法,不同的是在每个表达式之后写一个换行符。
<html>
<head>
<script type="text/javascript">
function createNewDoc()
{
var newDoc=document.open("text/html","replace");
var txt="<html><body>学习 DOM 非常有趣!</body></html>";
newDoc.write(txt);
newDoc.close();
}
</script>
</head>
<body>
<input type="button" value="打开并写入一个新文档" onclick="createNewDoc()">
</body>
</html>