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

相关推荐
半杯咖啡半行码1 分钟前
C++ 编程与 STL 模板:从泛型编程到内存安全详解
开发语言·c++
caoerzhong14 分钟前
JeeWMS 开源 WMS 部署避坑指南:Java 仓库管理系统的环境基线、四类根因与可复现交付
java·开发语言·开源
时间的拾荒人16 分钟前
Qt 界面优化:绘图详解 —— 从基础图形到图片处理
开发语言·qt·面试
MayZork34 分钟前
Qt 文件操作:QSaveFile 与 QTemporaryFile(含 QTemporaryDir)实战
开发语言·qt
北冥you鱼1 小时前
Go 语言空接口(interface{})使用场景与最佳实践
开发语言·windows·golang
xh didida1 小时前
Linux -- 基础IO
linux·服务器·开发语言·c++
个 人 练 习 生1 小时前
C++ string 类模拟实现:从底层理解字符串(上)
开发语言·c++·经验分享·学习·程序人生
2601_966949651 小时前
多市场量化策略的数据接口应该如何设计:从数据层架构到策略接入
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
小宋10211 小时前
A2UI从零实战:Agent安全生成交互界面与事件回传
javascript·人工智能·安全·交互
坤坤子吖1 小时前
C++智能指针:RAII、shared_ptr与内存泄漏
开发语言·c++·笔记·学习