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

相关推荐
触底反弹几秒前
🔥 字符串算法面试三连击:反转、回文、回文变种,搞懂这三题稳了!
前端·javascript·算法
触底反弹10 分钟前
AI Tool Use 深度解析:大模型是如何"突破物理限制"调用外部工具的?
javascript·人工智能·后端
竹林81822 分钟前
从 RPC 超时到批量签名:我用 @solana/web3.js 重构了一个 NFT 铸造页面,踩了这些坑
前端·javascript
aaaameliaaa25 分钟前
计算斐波那契数(递归、迭代)(1,1,2,3,5.....)
c语言·开发语言·笔记·算法·排序算法
m0_5474866631 分钟前
《模式识别:使用MATLAB分析与实现》全套PPT课件
开发语言·matlab·模式识别
Tim_1031 分钟前
【C++】009、extern关键字
java·开发语言
橘子星1 小时前
从零手写 RAG 语义检索:基于 Node.js 实现轻量级向量搜索
javascript·人工智能
林希_Rachel_傻希希1 小时前
web性能优化之————图片效果
前端·javascript·面试
橘子星1 小时前
基于 MCP 协议实现本地文件读取工具服务开发实践
javascript·人工智能
Darling噜啦啦1 小时前
前端存储与 this 指向完全指南:从 LocalStorage 实战到 call/apply/bind 深度解析
前端·javascript