有没有办法通过JavaScript获取所有现有HTML标记的列表?

时间:2017-11-01 01:23:13

标签: javascript

在训练营中有一个练习我正在参加哪个任务创建一个类似jQuery的选择器,这里是测试的一部分:

describe("selectorTypeMatcher", function() {
  it("should return the 'id' type for an id selector", function() {
    var type = selectorTypeMatcher('#pagetitle');
    expect(type).toEqual("id");
  });

  it("should return the 'class' type for a class selector", function() {
    var type = selectorTypeMatcher('.image');
    expect(type).toEqual("class");
  });

  it("should return the 'tag.class' type for a tag.class selector", function() {
    var type = selectorTypeMatcher('img.thumbnail');
    expect(type).toEqual("tag.class");
  });

  it("should return the 'tag' type for a tag selector", function() {
    var type = selectorTypeMatcher('div');
    expect(type).toEqual("tag");
  });
});

以下是我在测试规范中描述的创建的功能的一部分。

var selectorTypeMatcher = function(selector) {
  if (selector.includes('#')) return 'id';
  if (selector.indexOf('.') == 0) return 'class';
  if (/<[a-z][\s\S]*>/i.test() && selector.includes('.')) return 'tag.class';
};

我陷入条件状态,会检查标签和类,例如div.foo

我想创建了一个包含所有现有标签的数组......

var tags = ["a", "div", "span", "form", "h1", "h2", "h3", "h4"];

然后循环遍历它们,看看该值是否后跟一个.类,但这将是很多元素......

我想过利用document.querySelectorAll('*'),但那只是......

  

返回文档中元素的列表(使用depth-first   与指定匹配的文档节点的预订遍历   选择者组。返回的对象是NodeList。

但是就像它说 返回文档中元素的列表 ......

那么有API会返回所有现有的html元素吗?

html, head, body, div, p, span等。

的Merci!

2 个答案:

答案 0 :(得分:1)

您可以使用HTMLUnknownElement对象按规范检查有效标记:

if (tagIsValid(selector))
  return 'tag';

tagIsValid定义为:

function tagIsValid(tag) {
  tagChecked = document.createElement(tag).toString();
  return tagChecked != "[object HTMLUnknownElement]";
}

答案 1 :(得分:0)

if (selector.indexOf('.') > 0) return 'tag.class';
return 'tag';

我认为您可以以此结束它。