JavaScript DOM中Document对象常用属性与方法详解

作者:竹影

时间:2026-10-30

浏览:447

本文详解JavaScript中Document对象的常用属性与方法。涵盖anchors、URL、title等基础属性,以及createElement、getElementById、getElementsByClassName等核心DOM操作方法。通过具体代码示例,解析如何创建元素、获取节点及write输出,帮助开发者掌握DOM基础操作。

文章目录

Document对象概述

-----引入

当HTML文档加载到浏览器时,会自动生成对应的Document对象。

借助Document对象,脚本能够访问并操作HTML页面内的所有元素。

Document常用属性

属性

1. document.anchors:返回文档中所有Anchor对象的引用。此外,还有document.links、document.forms和document.images等类似属性。

2. document.URL:返回当前文档的完整URL地址。

3. document.title:返回当前文档的标题内容。

4. document.body:返回body元素节点。

Document常用方法

方法

1. document.close():用于关闭由document.open()打开的输出流,并显示选定的数据。


<!DOCTYPE html>
<html>
<head>
<script>
function createDoc()
{
var w=window.open();
w.document.open();
w.document.write("<h1>Hello World!</h1>");
w.document.close();
}
</script>
</head>

<body>
<input type="button" value="New document in a new window" onclick="createDoc()">
</body>
</html>

2. document.createElement():用于创建新的元素节点。


<!DOCTYPE html>
<html lang="en">
<!DOCTYPE html>
<head>
</head>
<body>
  <p>hello world</p>
  
<script>
  var a = document.createElement('hr');
  document.body.appendChild(a)


</script>
</body>
</html>

3. document.createAttribute():用于创建属性节点。


<!DOCTYPE html>
<html>
<body>

<p id="demo">Click the button to make a BUTTON element.</p>

<button onclick="myFunction()">Try it</button>

<script>

function myFunction()
{
var btn=document.createElement("BUTTON");
document.body.appendChild(btn);
};

</script>

</body>
</html>

4. document.createTextNode():用于创建文本节点。


<!DOCTYPE html>
<html lang="en">
<!DOCTYPE html>
<head>
</head>
<body>
  <p>hello world</p>

<script>
  var a = document.createTextNode('hahahah');
  document.body.appendChild(a)


</script>
</body>
</html>

5. document.getElementsByClassName():返回文档中所有指定类名的元素集合,结果为NodeList对象。NodeList是一种类似数组的数据结构,仅包含length属性,不具备push、pop等数组方法。

6. document.getElementById():返回拥有指定id的第一个对象的引用。

7. document.getElementsByName():返回带有指定名称的对象集合。

8. document.getElementsByTagName():返回带有指定标签名的对象集合。

9. document.write():向文档写入HTML表达式或JavaScript代码。需注意,若在HTML文档加载完成后使用write方法,其内容会覆盖原有的HTML文档。


<!DOCTYPE html>
<html lang="en">
<!DOCTYPE html>
<head>
</head>
<body>
  <p>hello world</p>

<script>
  document.write('hahahh')


</script>
</body>
</html>

以上就是小编为大家带来的js基础之DOM中document对象的常用属性方法详解全部内容了,希望大家多多支持本站~

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章