How would I generate a list of distinct HTML tags in a page using JavaScript (must work in IE6)

后端 未结 4 670
轮回少年
轮回少年 2021-01-28 10:53

The end result I\'m after is a JavaScript array containing a list of tag names that are used in the HTML document eg:

div, span, section, h1, h2, p, etc...

I wan

4条回答
  •  时光取名叫无心
    2021-01-28 11:41

    Here is a cross-browser solution:

    var tags = {};  // maintains object of tags on the page and their count
    var recurse = function(el) {
        // if element node
        if(el.nodeType == 1) {
            if(!tags[el.tagName])
                tags[el.tagName] = 0;
            tags[el.tagName]++;    
        }   
        // recurse through the children
        for(var i = 0, children = el.childNodes, len = children.length; i < len; i++) {
            recurse(children[i]);
        }
    }
    
    recurse(document);
    
    
    // if you want just what's in the body(included)
    var bodies = document.getElementsByTagName("body");
    for(var i = 0; i < bodies.length; i++)
        recurse(bodies[i]);
    

提交回复
热议问题