DWQA QuestionsCategory: ProgramThere is an HTML and an HTML in the document? How did this come about?
Bang Bang Peng asked 1 month ago

Today I come across such a problem
Complete the following functions: open a web page, such as Sina or Baidu, write a JS code, find all the elements beginning with H or h in the web page, and print the number of each element. If the web page contains head, HR and H2 elements, the result similar to the following will be printed:{hr: 3,h2: 2,head: 1}
My code is as follows

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));

I found a random web page and the output is as follows:

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

problem
Why is there an HTML and an HTML? Shouldn’t there be only one HTML in the normal code structure?
What is this HTML and how does it appear?

2 Answers
Naked little suckling dog answered 1 month ago

Node typeDo you think one of the nodetypes is 10

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

Bang Bang Peng replied 1 month ago

Oh, yes, I see. Thank you very much

chow answered 1 month ago

Print it document.childNodes There are two nodeNames, one is HTML, the other is HTML<!DOCTYPE html>

Bang Bang Peng replied 1 month ago

That’s it. I see. Thank you very much!