Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[js] 第1371天 使用js写一个方法遍历输出页面中的所有元素 #5328

Open
haizhilin2013 opened this issue Jan 15, 2023 · 2 comments
Labels
js JavaScript

Comments

@haizhilin2013
Copy link
Collaborator

第1371天 使用js写一个方法遍历输出页面中的所有元素

3+1官网

我也要出题

@haizhilin2013 haizhilin2013 added the js JavaScript label Jan 15, 2023
@zhanghang2017
Copy link

let doc = document
let head = [doc]

function bsf(head) {

while (head.length) {
let shift = head.shift()
console.log(shift.tagName)
head.push(...shift.childNodes)

}

}

@ShihHsing
Copy link

递归方法

function traverseElement(element) {
  // 遍历当前元素的子节点
  for (let i = 0; i < element.childNodes.length; i++) {
    const node = element.childNodes[i];
    // 判断当前节点是否是元素节点
    if (node.nodeType === 1) {
      console.log(node); // 输出当前元素
      traverseElement(node); // 递归遍历当前元素的子节点
    }
  }
}

// 调用方法开始遍历页面中的所有元素
traverseElement(document.documentElement);

循环方法

const stack = [document.documentElement];

while (stack.length > 0) {
  const element = stack.pop();
  // 遍历当前元素的子节点并将其压入栈中
  for (let i = 0; i < element.childNodes.length; i++) {
    const node = element.childNodes[i];
    if (node.nodeType === 1) {
      stack.push(node);
    }
  }
  console.log(element); // 输出当前元素
}

以上两种方法都可以遍历页面中的所有元素,并输出到控制台中。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
js JavaScript
Projects
None yet
Development

No branches or pull requests

3 participants