0

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 want the list to be distinct and I'm not interested in tags within the <head> of the document (but they can be there if it's a performance hog to exclude them).

This has to work in IE 6, 7, & 8 and I don't want to use jquery.

What would be the most efficient way of doing this?

4

4 回答 4

2

您正在寻找的是document.all.tagName 在我的脑海中,这样的 for 循环应该可以做到(前提是您要过滤该列表中不需要的标签)

for(i = 0; i < document.all.length; i++)
{
  console.log(document.all[i].tagName);
}
于 2012-10-18T05:11:10.487 回答
1

这是一个跨浏览器的解决方案:

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]);
于 2012-10-18T05:21:07.623 回答
0

要将文档中的唯一标记名列表作为一个数组获取,该数组适用于所有浏览器(回到 IE 6 和等效版本):

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

如果您认为可能存在与标记名称相同的继承对象属性,请使用propertyIsEnumerable测试:

      if (!tagCache.propertyIsEnumerable(tagname)) { 

所以它甚至可以在 Safari < 2 中工作。

于 2012-10-18T05:56:46.267 回答
0

获取文档中的所有标记名,唯一的,跨浏览器的,纯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;
 }
}

利用

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

排除<head>

于 2012-10-18T05:58:12.453 回答