欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

HTML DOM Document 对象

程序员文章站 2022-07-04 20:04:48
...

HTML DOM Document 对象

DOM(文档对象模型)是将html文档和编码语言(说白了就是javascript)结合起来的一种模型(与之相对应的bom就是将浏览器和编码语言结合起来的一种模型)

在了解Document 对象之前我们先来看一下什么是HTML DOM 节点

HTML DOM 节点

在 HTML DOM (Document Object Model) 中 , 每一个元素都是节点:

  • 文档是一个文档节点。
  • 所有的HTML元素都是元素节点。
  • 所有 HTML 属性都是属性节点。
  • 文本插入到 HTML 元素是文本节点。are text nodes。
  • 注释是注释节点。

 

Document 对象

当浏览器载入 HTML 文档, 它就会成为 Document 对象

Document 对象是 HTML 文档的根节点。

Document 对象使我们可以从脚本中对 HTML 页面中的所有元素进行访问。

提示:Document 对象是 Window 对象的一部分,可通过 window.document 属性对其进行访问。

 Document 对象属性和方法

这里只列举实例化几个常用的。

 

document.activeElement 返回当前获取焦点元素
document.baseURI 返回文档的绝对基础 URI
document.URL 返回文档完整的URL
document.body 返回文档的body元素
document.cookie 设置或返回与当前文档有关的所有 cookie。
document.doctype 返回与文档相关的文档类型声明 (DTD)。
document.documentElement 返回文档的根节点
document.documentURI 设置或返回文档的位置
document.getElementById() 返回对拥有指定 id 的第一个对象的引用。
document.getElementsByName() 返回带有指定名称的对象集合。
document.images 返回对文档中所有 Image 对象引用。
document.scripts 返回页面中所有脚本的集合。
document.write() 向文档写 HTML 表达式 或 JavaScript 代码。

 

 

实例

document.activeElement

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>activeElement属性</title>
<script>
function myFunction()
{
var x = document.activeElement.tagName;
document.getElementById("demo").innerHTML = x;
}
</script>
</head>
<body ondblclick="myFunction()">
<p>双击文档中的任意元素输出元素的标签名</p>
<input type="text" value="输入字段">
<button>按钮</button>
<p id="demo"></p>

</body>
</html>

 HTML DOM Document 对象

 document.baseURI

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>szfasfsdfaf</title>
</head>
<body>

<p id="demo">单击按钮显示基础URL</p>
<button onclick="myFunction()">点我</button>
<script>
function myFunction(){
	var x=document.getElementById("demo");
	x.innerHTML=document.baseURI;
}
</script>
<p><strong>注意:</strong> Internet Explorer不支持基础URI属性。</p>

</body>
</html>

 HTML DOM Document 对象

 

document.body 

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>huodebody</title>
</head>
<body>
<p>点击按钮修改当前文档的背景颜色</p>
<button onclick="myFunction()">点我</button>
<script>
function myFunction()
{
document.body.style.background="yellow";
}
</script>
</body>
</html>

HTML DOM Document 对象

 

 

document.cookie 

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>gsgsdgg</title>
</head>
<body>

与此文档相关的Cookies: 
<script>
document.write(document.cookie);
</script>

</body>
</html>