UNPKG

1.62 kBJavaScriptView Raw
1require('@webreflection/interface');
2
3const Node = require('./Node');
4const utils = require('./utils');
5
6const childrenType = node => node.nodeType === Node.ELEMENT_NODE;
7
8function asNode(node) {
9 return typeof node === 'object' ?
10 node :
11 this.createTextNode(node);
12}
13
14// interface ParentNode @ https://dom.spec.whatwg.org/#parentnode
15module.exports = Object.interface({
16
17 get children() {
18 return this.childNodes.filter(childrenType);
19 },
20
21 get firstElementChild() {
22 for (let i = 0, length = this.childNodes.length; i < length; i++) {
23 let child = this.childNodes[i];
24 if (child.nodeType === Node.ELEMENT_NODE) return child;
25 }
26 return null;
27 },
28
29 get lastElementChild() {
30 for (let i = this.childNodes.length; i--;) {
31 let child = this.childNodes[i];
32 if (child.nodeType === Node.ELEMENT_NODE) return child;
33 }
34 return null;
35 },
36
37 get childElementCount() {
38 return this.children.length;
39 },
40
41 prepend(...nodes) {
42 const fragment = this.ownerDocument.createDocumentFragment();
43 fragment.childNodes.push(...nodes.map(asNode, this.ownerDocument));
44 if (this.childNodes.length) {
45 this.insertBefore(fragment, this.firstChild);
46 } else {
47 this.appendChild(fragment);
48 }
49 },
50
51 append(...nodes) {
52 const fragment = this.ownerDocument.createDocumentFragment();
53 fragment.childNodes.push(...nodes.map(asNode, this.ownerDocument));
54 this.appendChild(fragment);
55 },
56
57 querySelector(css) {
58 return this.querySelectorAll(css)[0] || null;
59 },
60
61 querySelectorAll(css) {
62 return utils.querySelectorAll.call(this, css);
63 }
64
65});