FE-Interview
FE-Interview copied to clipboard
随便打开一个网页,用 JavaScript 打印所有以 s 和 h 开头的标签,并计算出标签的种类
扫描下方二维码,获取答案以及详细解析,同时可解锁800+道前端面试题。
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);
二维码挂了
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();