JS的Document属性和方法

在javascript中,document对象是一个非常重要的全局对象,它代表整个html文档。你可以通过document对象来访问和修改html文档的内容和结构。以下是一些常见的document属性和方法:

属性

1、document.title:获取或设置文档的标题,通常显示在浏览器的标题栏或标签上。

复制代码
document.title = "新的页面标题";

2、document.URL:获取文档的完整URL。

复制代码
console.log(document.URL);

3、document.documentElement:获取文档的根元素,通常是元素。

复制代码
console.log(document.documentElement);

4、document.body:获取文档的元素。

复制代码
console.log(document.body);

5、document.head:获取文档的元素。

复制代码
console.log(document.head);

6、document.referrer:获取导航到当前页面的前一个页面的URL。

复制代码
console.log(document.referrer);

方法

1、document.getElementById(id):根据指定的id获取元素。

复制代码
var element = document.getElementById("myElementId");

2、document.getElementsByClassName(className):根据指定的类名获取元素集合。

复制代码
var elements = document.getElementsByClassName("myClassName");

3、document.getElementsByTagName(tagName):根据指定的标签名获取元素集合。

复制代码
var elements = document.getElementsByTagName("div");

4、document.querySelector(selector):返回文档中匹配指定CSS选择器的第一个Element元素。

复制代码
var element = document.querySelector(".myClass");

5、document.querySelectorAll(selector):返回文档中匹配指定CSS选择器的所有Element元素的NodeList(静态的)。

复制代码
var elements = document.querySelectorAll(".myClass");

6、document.createElement(tagName):创建一个新的元素。

复制代码
var newElement = document.createElement("div");

7、document.createTextNode(text):创建一个新的文本节点。

复制代码
var textNode = document.createTextNode("Hello, world!");

8、document.appendChild(node):向文档的某个元素追加子节点。

复制代码
someElement.appendChild(newElement);

9、document.removeChild(node):从文档中移除某个子节点。

复制代码
someElement.removeChild(childElement);

10、document.write(content):向文档写入HTML表达式或JavaScript代码。

复制代码
document.write("<p>这是一个段落。</p>");

这只是document对象的一部分属性和方法。实际上,document对象提供了许多其他的功能和方法,用于处理HTML文档的内容和结构。

相关推荐
空堂与归7 分钟前
单机 Python 跑不动?Ray 分布式计算框架让 AI 训练提速 10 倍
开发语言·人工智能·python
JacksonMx14 分钟前
Java 线程池:复用、Spring 管理、监控与线上故障排查全指南
开发语言·python
BioRunYiXue21 分钟前
RACE技术全攻略:从全长克隆到靶基因验证
java·javascript·网络·人工智能·科技·算法·eclipse
脉动数据行情22 分钟前
Python WebSocket 实现融通金实时行情监听
开发语言·python·websocket
only-qi23 分钟前
Python Agent 开发速通清单
开发语言·python
zq_638930 分钟前
ObjectModel_diagram.pdf 文档详细总结
开发语言·matlab
IMPYLH32 分钟前
HTML 的 <ins> 元素
前端·javascript·html
晨米酱38 分钟前
Umi Mock 如何从文件声明变成 HTTP 响应
前端·javascript·设计
01_ice1 小时前
前端学习JS(3)
前端·javascript·学习
Hilaku1 小时前
外包前端和大厂前端,写的代码到底有什么本质区别?
前端·javascript·程序员