FE-Interview icon indicating copy to clipboard operation
FE-Interview copied to clipboard

随便打开一个网页,用 JavaScript 打印所有以 s 和 h 开头的标签,并计算出标签的种类

Open lgwebdream opened this issue 5 years ago • 4 comments

lgwebdream avatar Jul 06 '20 15:07 lgwebdream

扫描下方二维码,获取答案以及详细解析,同时可解锁800+道前端面试题。

lgwebdream avatar Jul 06 '20 15:07 lgwebdream

const tmp = new Set()
Array.prototype.slice.call(document.querySelectorAll("*")).forEach(v => {
    const tagName = v.tagName.toLowerCase()
    if (tagName[0] === 's' || tagName[0] === 'h') {
        tmp.add(v.tagName)
    }
})
console.log(tmp);

Carnia avatar Feb 15 '22 14:02 Carnia

二维码挂了

mingwong1278 avatar Sep 05 '23 06:09 mingwong1278


const printTags = () => {
  const body = document.getElementsByTagName("body")[0];
  const tags = new Map();

  const dp = node => {
    if (node.tagName.startsWith("S") || node.tagName.startsWith("H")) {
      if (tags.has(node.tagName)) {
        const value = tags.get(node.tagName);
        value.push(node);
        tags.set(node.tagName, value);
      } else {
        tags.set(node.tagName, [node]);
      }
    }

    if (node.children.length > 0) {
      for (let index = 0; index < node.children.length; index++) {
        const child = node.children[index];
        dp(child);
      }
    }
  };

  dp(body);

  tags.forEach((nodes, key) => {
    console.log(`key: ${key}, 共: ${nodes.length} 个`);
    nodes.forEach(node => {
      console.log(node);
    });
  });
};

printTags();

gaohan1994 avatar May 06 '24 09:05 gaohan1994