Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

今天遇到这样一道题
完成以下功能:任意打开一个网页如新浪或者百度,写一段js代码找到网页中所有以h或者H开头的元素,并打印每种元素的个数,如网页中含有head, hr 和 h2 元素,那么打印出类似如下的结果:

{

hr: 3,

h2: 2,

head: 1

}
我的代码如下

function find(node,map = {}){
    let tagName = node.nodeName;
    let first = tagName.slice(0,1);
    if( first=='H'|| first == "h"){
        if(map[tagName]){
            map[tagName]++;
        }else{
            map[tagName] = 1;
        }
    }
    let children = node.childNodes;
    if(children){
        for(let i = 0;i < children.length; i++){
            find(children[i],map);
        }
    }
    return map;
}
console.log(find(document));

我随便找了一个网页输出结果如下:

{html: 1, HTML: 1, HEAD: 1, H3: 2}

问题
为什么会有一个HTML和一个html呢,正常代码结构中不是只应该有一个html吗?
请问这个HTML是什么,怎么出现的?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
2.8k views
Welcome To Ask or Share your Answers For Others

1 Answer

Node type

你看其中一个nodeType是不是 10

A DocumentType node, such as <!DOCTYPE html>.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...