Skip to content
Advertisement

Is there a way to get a list of all existing HTML tags via JavaScript?

There is an exercise in a bootcamp I am attending which tasks one to create a jQuery like selector, here is part of the test:

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

The following is part of function which I created as described in the test spec.

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

I am stuck at the conditional which would check for a tag and class e.g. div.foo

I thought of created an array which would contain all existing tags…

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

And then loop over them and see if that value was followed by an . for a class but that would be a lot of elements…

I thought of leveraging document.querySelectorAll('*') but that just…

Returns a list of the elements within the document (using depth-first pre-order traversal of the document’s nodes) that match the specified group of selectors. The object returned is a NodeList.

But like it says Returns a list of the elements within the document

So is there an API that will return all of the existing html elements?

html, head, body, div, p, span etc.

Merci!

Advertisement

Answer

You can use HTMLUnknownElement object to check for a valid tag by specification:

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

and tagIsValid definition would be:

function tagIsValid(tag) {
  tagChecked = document.createElement(tag).toString();
  return tagChecked != "[object HTMLUnknownElement]";
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement