// 示例代码:使用 JavaScript 查找子节点
// 假设我们有一个 HTML 结构如下:
/*
<div id="parent">
<p class="child">Child Paragraph 1</p>
<span class="child">Child Span</span>
<p class="child">Child Paragraph 2</p>
</div>
*/
// 获取父节点
const parent = document.getElementById('parent');
// 方法 1: 使用 children 属性获取所有子元素(只包括元素节点)
const childElements = parent.children;
console.log(childElements); // 返回一个 HTMLCollection,包含所有的子元素
// 方法 2: 使用 querySelectorAll 获取特定类名的子节点
const childNodesWithClass = parent.querySelectorAll('.child');
console.log(childNodesWithClass); // 返回一个 NodeList,包含所有带有 .child 类的子节点
// 方法 3: 使用 childNodes 属性获取所有类型的子节点(包括文本节点和注释节点)
const allChildNodes = parent.childNodes;
console.log(allChildNodes); // 返回一个 NodeList,包含所有的子节点,包括文本节点和元素节点
children:返回的是一个 HTMLCollection,它只包含元素节点(如 <p>、<span> 等),不包括文本节点或注释节点。querySelectorAll:可以根据选择器(如类名、标签名等)来查找特定的子节点,并返回一个 NodeList。childNodes:返回的是一个 NodeList,它包含所有类型的子节点,包括元素节点、文本节点和注释节点。上一篇:js 转数组
下一篇:js json添加元素
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站