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文档的内容和结构。

相关推荐
代码煮茶16 小时前
React 组件封装方法论 —— 以 Todo App 为例
javascript·react.js
任沫17 小时前
Agent之Function Call
javascript·人工智能·go
默_笙18 小时前
🛬 我让 AI 帮我写了一个打飞机游戏,结果 Canvas 把我整不会了
前端·javascript
梯度不陡18 小时前
AI 到底能不能从零写软件?ProgramBench 和 RepoZero 给出了两种答案
前端·javascript·面试
胡萝卜术20 小时前
滑动窗口最大值:从暴力到单调队列,层层优化全解析
前端·javascript·面试
kyriewen21 小时前
2026 年了,这 6 个 npm 包可以卸载了——浏览器原生 API 已经能替代
前端·javascript·npm
铁皮饭盒1 天前
bun直接tsx,优雅!
javascript·后端
_柳青杨1 天前
一文吃透 Node.js 事件循环:从原理到 Node 20+ 重大变更
javascript·后端
JieE2121 天前
LeetCode 101. 对称二叉树|JS 递归 + 迭代双解法,彻底搞懂镜像判断
javascript·算法
冬奇Lab2 天前
AI Workflow 定义的四次演进:从 Markdown 到 JS 脚本,再到分布式多 Agent
javascript·人工智能·agent