Skip to content

Commit

Permalink
feat: implement Element.querySelector/querySelectorAll
Browse files Browse the repository at this point in the history
  • Loading branch information
b-fuze committed Oct 14, 2020
1 parent c0a1ad4 commit adaa5a5
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/dom/document.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,12 @@ export class Document extends Node {
setLock(true);
}

// Expose the document's NWAPI for Element's access to
// querySelector/querySelectorAll
get _nwapi() {
return this.#nwapi;
}

get documentURI() {
return this.#documentURI;
}
Expand Down
21 changes: 21 additions & 0 deletions src/dom/element.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { getLock } from "../constructor-lock.ts";
import { fragmentNodesFromString } from "../deserialize.ts";
import { Node, NodeType, Text } from "./node.ts";
import { NodeList, nodeListMutatorSym } from "./node-list.ts";

export class DOMTokenList extends Set<string> {
contains(token: string): boolean {
Expand Down Expand Up @@ -261,6 +262,26 @@ export class Element extends Node {
return prev;
}

querySelector(selectors: string): Element | null {
if (!this.ownerDocument) {
throw new Error("Element must have an owner document");
}

return this.ownerDocument!._nwapi.first(selectors, this);
}

querySelectorAll(selectors: string): NodeList {
if (!this.ownerDocument) {
throw new Error("Element must have an owner document");
}

const nodeList = new NodeList();
const mutator = nodeList[nodeListMutatorSym]();
mutator.push(...this.ownerDocument!._nwapi.select(selectors, this))

return nodeList;
}

// TODO: DRY!!!
getElementById(id: string): Element | null {
for (const child of this.childNodes) {
Expand Down

0 comments on commit adaa5a5

Please sign in to comment.