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

相关推荐
JieE21210 小时前
LeetCode 226. 翻转二叉树|JS 递归超详细拆解,二叉树入门经典题
javascript·算法
JieE21210 小时前
LeetCode 104. 二叉树的最大深度|递归思路超详细拆解
javascript·算法
kyriewen14 小时前
我用 AI 一周写完了整个项目,上线第一天就崩了——这是我踩过最贵的 5 个坑
前端·javascript·ai编程
Larcher14 小时前
AI Loop:让AI像人一样自主完成任务的核心机制
javascript·人工智能·设计模式
默_笙14 小时前
🃏 JS 只有 8 种数据类型,但我花了 2 天才搞懂 null 和 undefined 的区别
javascript
jump_jump15 小时前
流式 HTML:从 htmx 片段装配到浏览器原生增量渲染
javascript·性能优化·前端工程化
swipe16 小时前
正则表达式入门到进阶:从表单校验到手写模板引擎
前端·javascript·面试
kyriewen17 小时前
前端错误监控最全指南:捕获 JS 异常、Promise 拒绝、资源加载失败,附上报代码
前端·javascript·监控
大家的林语冰17 小时前
ESLint 近期动态大全,新版本正式发布,antfu 大佬推荐的插件也更新了!
前端·javascript·前端工程化
胡志辉18 小时前
深入浅出 call、apply、bind
前端·javascript·后端