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][\s\S]*>/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!
Array.from(new Set(Array.from(document.querySelectorAll('*'), node => node.nodeName)))queryselectorAll. It returns all of the HTML elements because all elements exist within the document. JQuery usesquerySelectorAllinternally.Object.getOwnPropertyNames(window).filter(k=>{ try{ return HTMLElement.isPrototypeOf(window[k])} catch(e){} })but to get their tagName would require being able to create these, which must be done withDocument.createElement(tagName)... Oh and actually this code will also return HTMLMediaElement, which is the proto of other HTMLElements, so it's not entirely reliable either...