javascript递归null TypeError在while循环体中,该循环为';这是不可能被执行的
很抱歉问你这个新手问题 我做了一些实验,尝试以不同的方式实现walkTheDOM函数。这是我写的,我有一个问题:javascript递归null TypeError在while循环体中,该循环为';这是不可能被执行的,javascript,Javascript,很抱歉问你这个新手问题 我做了一些实验,尝试以不同的方式实现walkTheDOM函数。这是我写的,我有一个问题: function walkTheDOM(root) { console.log(root); node = root.firstElementChild; while (node) { console.log('hey') walkTheDOM(node); console.log('hey2');
function walkTheDOM(root) {
console.log(root);
node = root.firstElementChild;
while (node) {
console.log('hey')
walkTheDOM(node);
console.log('hey2');
node = node.nextElementSibling;
}
}
walkTheDOM(document.body);
我在一台计算机上运行了这个:
你的逻辑似乎很好。问题是您已将
节点
声明为全局变量,这就是为什么当您递归调用walkTheDOM
时,节点
会被重新分配并变为null
。您只需在节点之前添加let
:
函数walkTheDOM(根){
console.log(root);
让node=root.firstElementChild;
while(节点){
console.log('hey')
步行区(节点);
console.log('hey2');
node=node.nextElementSibling;
}
}
walkTheDOM(document.body)代码>
Script snippet %232:2 <body class="page job-posting-page " data-analytics-page="careers" data-analytics-section="work-for-twitter" data-analytics-component="201901/data-science-manager-platform-manipulation0" data-analytics-element="page" style="border: 1px solid red;">…</body>
Script snippet %232:5 hey
Script snippet %232:2 <div id="page-wrapper">…</div>
Script snippet %232:5 hey
Script snippet %232:2 <div id="loader-container">…</div>
Script snippet %232:5 hey
Script snippet %232:2 <div id="loader" class></div>
Script snippet %232:7 hey2
Script snippet %232:8 Uncaught TypeError: Cannot read property 'nextElementSibling' of null
at walkTheDOM (VM51636 Script snippet %232:8)
at walkTheDOM (VM51636 Script snippet %232:6)
at walkTheDOM (VM51636 Script snippet %232:6)
at VM51636 Script snippet %232:12
function walkTheDOM(node, func) {
func(node);
node = node.firstChild;
while (node) {
walkTheDOM(node, func);
node = node.nextSibling;
}
}
// Example usage: Process all Text nodes on the page
walkTheDOM(document.body, function (node) {
if (node.nodeType === 3) { // Is it a Text node?
var text = node.data.trim();
if (text.length > 0) { // Does it have non white-space text content?
// process text
}
}
});