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

后端 未结 4 663
轮回少年
轮回少年 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:28

    Get all tagnames in the document, unique, crossbrowser, plain js:

    var els = document.getElementsByTagName('*'), tags = [], tmp = {}
    for (var i=0;i<els.length;i+=1){
     if (!(els[i].tagName in tmp)){
       tags.push(els[i].tagName);
       tmp[els[i].tagName] = 1;
     }
    }
    

    use

    if (!(els[i].tagName in tmp) 
         && !/head/i.test(els[i].parentNode.tagName) 
         && !/html|head/i.test(els[i].tagName))
    

    to exclude the <head>

    0 讨论(0)
  • 2021-01-28 11:37

    To get a unique list of tagnames in a document as an array that works in all browsers back to IE 6 and equivalent:

    function listTagNames() {
      var el, els = document.body.getElementsByTagName('*');
      var tagCache = {};
      var tagname, tagnames = [];
    
      for (var i=0, iLen=els.length; i<iLen; i++) {
        tagname = els[i].tagName.toLowerCase();
    
        if ( !(tagname in tagCache) ) {
          tagCache[tagname] = tagname;
          tagnames.push(tagname);
        }  
      }
      return tagnames;
    }
    

    If you think there might be an inherited object property that is the same as a tag name, use a propertyIsEnumerable test:

          if (!tagCache.propertyIsEnumerable(tagname)) { 
    

    so it will work even in Safari < 2.

    0 讨论(0)
  • 2021-01-28 11:41

    What you're looking for is document.all.tagName At the top of my head, a for loop like this should do it (providing that you're gonna filter the tags you don't want on that list)

    for(i = 0; i < document.all.length; i++)
    {
      console.log(document.all[i].tagName);
    }
    
    0 讨论(0)
  • 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]);
    
    0 讨论(0)
提交回复
热议问题