UNPKG

1.3 kBJavaScriptView Raw
1"use strict";
2
3const {NodeList} = require("./NodeList");
4
5module.exports = {
6 HTMLCollection,
7 getElementsByClassName,
8 getElementsByTagName,
9};
10
11function HTMLCollection(parentElement, selector, options = { attributes: true }) {
12 const list = new NodeList(parentElement, selector, {
13 ...options,
14 });
15 list.item = function item() {};
16 list.namedItem = function item() {};
17
18 Object.setPrototypeOf(list, HTMLCollection.prototype);
19
20 return list;
21}
22
23HTMLCollection.prototype.length = function length() {};
24HTMLCollection.prototype.item = function item() {};
25HTMLCollection.prototype.namedItem = function namedItem() {};
26
27function getElementsByClassName(parentElement, classNames) {
28 const selectors = classNames && classNames.trim().replace(/\s+/g, ".");
29 const noMatch = Array(30).fill("no").join("");
30 const selector = selectors.split(".").reduce((result, sel) => {
31 if (/-?[_a-zA-Z]+[_a-zA-Z0-9-]*/.test(sel)) result += `.${sel}`;
32 else result += noMatch;
33 return result;
34 }, "");
35 return new HTMLCollection(parentElement, selector, {attributes: true});
36}
37
38function getElementsByTagName(parentElement, tagName) {
39 const selector = tagName && tagName.trim().match(/^([_a-zA-Z]+[_a-zA-Z0-9-]*)$/)[1];
40 return new HTMLCollection(parentElement, selector, {attributes: false});
41}