// 获取 HTMLCollection 示例
// 1. 使用 getElementsByTagName 方法
const elements = document.getElementsByTagName('p');
console.log(elements); // 返回一个 HTMLCollection,包含所有的 <p> 元素
// 解释:getElementsByTagName 返回一个 HTMLCollection,它是一个类数组对象,包含了文档中所有指定标签名的元素。HTMLCollection 是动态的,意味着如果 DOM 发生变化,它会自动更新。
// 2. 使用 getElementsByClassName 方法
const elementsByClass = document.getElementsByClassName('my-class');
console.log(elementsByClass); // 返回一个 HTMLCollection,包含所有 class 为 'my-class' 的元素
// 解释:getElementsByClassName 返回一个 HTMLCollection,它包含了文档中所有指定类名的元素。同样,HTMLCollection 是动态的。
// 3. 使用 children 属性
const parentElement = document.querySelector('.parent');
const childElements = parentElement.children;
console.log(childElements); // 返回一个 HTMLCollection,包含父元素下的所有子元素
// 解释:children 属性返回一个 HTMLCollection,它包含了当前元素的所有子元素。
上一篇:html美化工具
下一篇:html 教程
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站