我需要一些帮助来编写查找一个元素的后代数量的逻辑。
html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<main>
<ul>
<li><button>item</button></li>
</ul>
<p>Hello, world</p>
</main>
<script src="index.js"></script>
</body>
</html>
index.js:
function countDescendants(element) {}
// Test code
const result = countDescendants(document.querySelector("main"));
if (result !== 4) {
console.error(`fail: ${result}`);
} else {
console.log("Pass!");
}
可以帮我写一些countDescendants function.We不能使用的内置函数吗?应该写我们自己的逻辑。对于这个特定的例子,它应该返回结果4。
发布于 2020-03-29 17:20:44
如果你想要所有的孩子和后代,最简单的方法就是这样使用querySelectorAll:
document.querySelectorAll('main *').length
完整代码:
// Test code
const result = document.querySelectorAll("main *").length;
if (result !== 4) {
console.log(`fail: ${result}`);
} else {
console.log("Pass!");
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<main>
<ul>
<li><button>item</button></li>
</ul>
<p>Hello, world</p>
</main>
<script src="index.js"></script>
</body>
</html>
发布于 2020-03-31 00:23:02
下面的代码使用每个元素的.children
属性,递归地遍历DOM树,并在遍历过程中对子元素进行计数。
function countDescendants(el) {
function countChildren({ children }) {
let count = 0
if(!children.length) return 0
for(let el of [...children]) {
count++
count += countChildren(el)
}
return count
}
return countChildren(el)
}
const result = countDescendants(document.querySelector('main'))
console.log(result) // 4
<main>
<ul>
<li><button>item</button></li>
</ul>
<p>Hello, world</p>
</main>
发布于 2021-11-09 12:41:48
Element
方法querySelectorAll()
返回一个静态(非实时)NodeList
,表示与指定的选择器组匹配的元素列表,这些选择器是调用该方法的元素的后代。
function countDescendants(el) {
return el.querySelectorAll('*').length
}
https://stackoverflow.com/questions/60912177
复制相似问题