JS2-DOM API

一.选择元素:

  • document.getElementById(id):通过 ID 选择唯一元素。

  • document.getElementsByClassName(className):通过类名选择元素集合(HTMLCollection)。

  • document.getElementsByTagName(tagName):通过标签名选择元素集合(HTMLCollection)。

  • document.querySelector(selector):通过 CSS 选择器选择第一个匹配元素

  • document.querySelectorAll(selector):通过 CSS 选择器选择所有匹配元素(NodeList)。

  • element.querySelector/querySelectorAll:在指定元素的子节点中选择元素。

二.创建/插入/删除元素

  • document.createElement(tagName):创建新元素。

  • document.createTextNode(text):创建文本节点。

  • parent.appendChild(child):在父元素末尾插入子元素。

  • parent.insertBefore(newNode, referenceNode):在参考节点前插入新节点。

  • parent.removeChild(child):删除子元素(需通过父元素操作)。

  • element.remove():直接删除元素自身(ES6+)。

  • element.cloneNode(deep):复制元素(deep=true 复制子节点)。

<div id="parent">
   <p>原有内容</p>
</div>
<script>
   const original = parent.querSelector("p")
   const clone = original.cloneNode(true);//复制
   parent.appendChild(clone)//复制后插入
</script>

三.修改元素属性/内容

  • element.innerHTML:设置或获取元素的 HTML 内容(包含标签)。

  • element.textContent:设置或获取元素的纯文本内容(忽略标签)。

  • element.setAttribute(attr, value):设置元素属性(如 srcclass)。

  • element.getAttribute(attr):获取元素属性值。

  • element.removeAttribute(attr):移除元素属性。

  • 直接操作属性:element.srcelement.classNameelement.id 等。

<img id="myImg" src="old.jpg" alt="旧图片">
<p id="content">原始文本</p>
<script>
   const img = document.getElementById("myImg")
   const para = document.getElementById("content")
img.setAttribute("src","new.jpg")
img.setAttribute("alt","新图片")
img.getAttribute("src")//获取属性值->"new.jpg"

</script>

四.样式操作

  • element.style.property:设置或获取元素的行内样式(如 element.style.color = "red")。

  • element.classList.add(className):添加类名。

  • element.classList.remove(className):移除类名。

  • element.classList.toggle(className):切换类名(存在则移除,不存在则添加)。

  • element.classList.contains(className):判断是否包含类名。

五.DOM关系

  • element.parentNode:获取父节点。

  • element.childNodes:获取所有子节点(包含文本 / 注释节点,NodeList)。

  • element.children:获取所有子元素(仅元素节点,HTMLCollection)。

  • element.previousSibling/nextSibling:获取前 / 后相邻节点(可能是文本节点)。

  • element.previousElementSibling/nextElementSibling:获取前 / 后相邻元素节点。

六.事件API

  1. 事件绑定

  • element.addEventListener(eventType, handler, useCapture):绑定事件(推荐)。

    • eventType:事件类型(如 clickkeydown,不带 on 前缀)。

    • handler:事件处理函数(接收 event 对象)。

    • useCapture:是否在捕获阶段触发(默认 false,冒泡阶段)。

  • 移除事件:element.removeEventListener(eventType, handler)

2.常用事件类型

  • 鼠标事件

点击:click

双击:dbclick

按下:mousedown

松开:mouseup

移动:mousemove

进入:mouseenter

离开:mouseleave

  • 键盘事件

按键按下:keydown

按键松开:keyup

  • 表单事件:

表单提交:submit

输入变化:input

值改变且失焦:change

获得焦点:focus

失去焦点:blur

  • 文档事件:

DOM加载完成:DOMContentLoaded

页面资源加载完成:load

窗口大小变化:resize

滚动:scroll

<button id="btn">点击我</button>
<input type="text" id="input">
<form id="myForm">
  <input type="text" name="username">
  <button type="submit">提交</button>
</form>
// 1. 点击事件
const btn = document.getElementById("btn");
btn.addEventListener("click", function(event) {
  console.log("按钮被点击了");
  console.log("触发元素:", event.target); // 指向按钮
});

// 2. 键盘事件
const input = document.getElementById("input");
input.addEventListener("keydown", (e) => {
  if (e.key === "Enter") {
    console.log("输入框按了回车,内容:", input.value);
  }
});

// 3. 表单提交(阻止默认行为)
const form = document.getElementById("myForm");
form.addEventListener("submit", (e) => {
  e.preventDefault(); // 阻止表单默认提交(避免页面刷新)
  console.log("表单提交了,用户名:", form.username.value);
});

// 4. 鼠标事件
document.addEventListener("mousemove", (e) => {
  // 实时显示鼠标在视口的坐标
  console.log(`X: ${e.clientX}, Y: ${e.clientY}`);
});

3.事件对象

  • event.target:触发事件的原始元素。

  • event.currentTarget:绑定事件的元素(当前处理者)。

  • event.preventDefault():阻止默认行为(如链接跳转、表单提交)。

  • event.stopPropagation():阻止事件冒泡。

  • event.key:键盘事件中按下的键(如 Entera)。

  • event.clientX/clientY:鼠标事件中相对于视口的坐标。

七.BOM操作API

1.window 对象(全局对象)

  • window.alert(message):弹出警告框。

  • window.confirm(message):弹出确认框(返回 true/false)。

  • window.prompt(message, defaultValue):弹出输入框(返回输入值或 null)。

  • window.open(url, name, features):打开新窗口(features 可设置尺寸等)。

  • window.close():关闭当前窗口。

  • window.setTimeout(callback, delay):延迟指定毫秒后执行函数(返回定时器 ID)。

  • window.setInterval(callback, interval):每隔指定毫秒重复执行函数(返回定时器 ID)。

  • window.clearTimeout(id)/clearInterval(id):清除定时器。

//定时器
const timer = setTimeout(()=>{
  console.log("2秒后执行)
},2000)
setInterVal(()=>{
  console.log("每隔一秒执行一次")
},1000)

clearTimeout(timer)//清除定时器

location.href = "https://baidu.com";//直接跳转页面

2.location 对象(地址栏信息)

  • location.href:获取或设置完整 URL(如 location.href = "https://example.com" 跳转页面)。

  • location.reload():刷新页面(true 强制从服务器刷新)。

  • location.search:获取 URL 中 ? 后的查询字符串(如 ?id=1&name=test)。

  • location.hash:获取 URL 中 # 后的哈希值(如 #section1)。

3.history对象(浏览历史)

  • history.back():后退到上一页(同浏览器 “后退” 按钮)。

  • history.forward():前进到下一页(同浏览器 “前进” 按钮)。

  • history.go(n):跳转 n 页(n=1 前进,n=-1 后退)。

4.scteen对象(屏幕信息)

  • screen.width/screen.height:屏幕分辨率。

  • screen.availWidth/screen.availHeight:可用屏幕尺寸(不含任务栏)。

八.数组API

1.遍历/迭代

  • array.forEach((item,index,arr)=>{}):遍历数组(无返回值)。

  • array.map((item) => {}):返回新数组,每个元素为回调处理结果。

  • array.filter((item) => {}):返回符合条件的元素组成的新数组。

  • array.find((item) => {}):返回第一个符合条件的元素。

  • array.findIndex((item) => {}):返回第一个符合条件的元素索引。

  • array.some((item) => {}):判断是否有至少一个元素符合条件(返回 true/false)。

  • array.every((item) => {}):判断是否所有元素都符合条件(返回 true/false)。

2.修改/转换

  • array.push(...items):在末尾添加元素(返回新长度)。

  • array.pop():删除末尾元素(返回被删除元素)。

  • array.unshift(...items):在开头添加元素(返回新长度)。

  • array.shift():删除开头元素(返回被删除元素)。

  • array.slice(start, end):截取子数组(不改变原数组,end 不包含)。

  • array.splice(start, deleteCount, ...items):删除 / 添加元素(改变原数组,返回被删除元素)。

  • array.join(separator):将数组转为字符串(用分隔符连接)。

  • array.concat(array2):合并数组(返回新数组)。

3.排序/反转

  • array.sort((a, b) => a - b):排序(默认按字符串排序,需传入比较函数)。

  • array.reverse():反转数组(改变原数组)。

4.其他

  • array.includes(item):判断数组是否包含指定元素(返回 true/false)。

  • array.indexOf(item):返回元素第一次出现的索引(不存在返回 -1)。

  • array.reduce((acc, item) => {}, initialValue):累加器,将数组转为单个值(如求和、去重)。

const arr = [1, 2, 3, 4, 5];

// 1. 遍历与转换
const doubled = arr.map(item => item * 2); // [2,4,6,8,10]
const evens = arr.filter(item => item % 2 === 0); // [2,4]
const sum = arr.reduce((acc, item) => acc + item, 0); // 15

// 2. 添加/删除元素
arr.push(6); // [1,2,3,4,5,6]
arr.pop(); // 移除最后一个 → [1,2,3,4,5]
arr.unshift(0); // [0,1,2,3,4,5]
arr.shift(); // 移除第一个 → [1,2,3,4,5]

// 3. 截取与替换
const slice = arr.slice(1, 3); // [2,3](不改变原数组)
const splice = arr.splice(1, 2, 10); // 从索引1删除2个,插入10 → 原数组变为 [1,10,4,5],返回被删除的 [2,3]

// 4. 判断
console.log(arr.includes(10)); // true
console.log(arr.find(item => item > 3)); // 4

九.字符串API

1.查找/判断

  • str.indexOf(substr):返回子串第一次出现的索引(不存在返回 -1)。

  • str.lastIndexOf(substr):返回子串最后一次出现的索引。

  • str.includes(substr):判断是否包含子串(返回 true/false)。

  • str.startsWith(prefix):判断是否以指定前缀开头。

  • str.endsWith(suffix):判断是否以指定后缀结尾。

2.截取/分割

  • str.slice(start, end):截取子串(end 不包含,支持负数)。

  • str.substring(start, end):类似 slice,但不支持负数。

  • str.substr(start, length):从 start 开始截取指定长度(ES6 后不推荐)。

  • str.split(separator):按分隔符分割为数组(如 'a,b,c'.split(',')['a','b','c'])。

3.转换/修改

  • str.toUpperCase():转为大写。

  • str.toLowerCase():转为小写。

  • str.trim():去除首尾空格。

  • str.replace(regexp/substr, replacement):替换子串(支持正则)。

  • str.repeat(n):重复字符串 n 次(ES6+)。

十.JSON API

  • JSON.stringify(obj):将 JavaScript 对象转为 JSON 字符串(注意:函数、undefined 会被忽略)。

  • JSON.parse(str):将 JSON 字符串转为 JavaScript 对象(若格式错误会报错)。

十一.存储API

  1. localStorage

  • 永久存储(除非手动清除)。

  • localStorage.setItem(key, value):存储数据(value 需为字符串,对象需用 JSON.stringify 转换)。

  • localStorage.getItem(key):获取数据(返回字符串,对象需用 JSON.parse 转换)。

  • localStorage.removeItem(key):删除指定键数据。

  • localStorage.clear():清空所有数据。

2.sessionStorage

  • 会话级存储(关闭标签页后清除),用法与 localStorage 完全一致。

十二.定时器API

  • setTimeout(callback, delay):延迟 delay 毫秒后执行 callback(返回定时器 ID)。

  • setInterval(callback, interval):每隔 interval 毫秒重复执行 callback(返回定时器 ID)。

  • clearTimeout(id):清除 setTimeout 定时器。

  • clearInterval(id):清除 setInterval 定时器。

十三.其他常用

  • 日期(Date)new Date() 创建日期对象,getFullYear()getMonth()getDate() 等获取日期信息。

  • 数学(Math)Math.random()(随机数)、Math.floor()(向下取整)、Math.ceil()(向上取整)、Math.max()/Math.min()(最大 / 最小值)。

  • 类数组转换Array.from(likeArray) 将类数组(如 NodeList)转为数组。

  • 展开运算符... 用于数组 / 对象的展开或复制(ES6+)


JS2-DOM API
http://localhost:8090//archives/js2-domcao-zuo
作者
王雅慧
发布于
2025年11月02日
许可协议