/
HTMLOptionsCollection.ts
108 lines (95 loc) · 2.4 KB
/
HTMLOptionsCollection.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import DOMException from '../../exception/DOMException';
import HTMLCollection from '../element/HTMLCollection';
import IHTMLOptGroupElement from '../html-opt-group-element/IHTMLOptGroupElement';
import IHTMLSelectElement from '../html-select-element/IHTMLSelectElement';
import IHTMLOptionElement from './IHTMLOptionElement';
import IHTMLOptionsCollection from './IHTMLOptionsCollection';
/**
* HTML Options Collection.
*
* Reference:
* https://developer.mozilla.org/en-US/docs/Web/API/HTMLOptionsCollection.
*/
export default class HTMLOptionsCollection
extends HTMLCollection
implements IHTMLOptionsCollection
{
private _selectElement: IHTMLSelectElement;
private _selectedIndex = -1;
/**
*
* @param selectElement
*/
constructor(selectElement: IHTMLSelectElement) {
super();
this._selectElement = selectElement;
}
/**
* Returns selectedIndex.
*
* @returns SelectedIndex.
*/
public get selectedIndex(): number {
return this._selectedIndex;
}
/**
* Sets selectedIndex.
*
* @param selectedIndex SelectedIndex.
*/
public set selectedIndex(selectedIndex: number) {
if (typeof selectedIndex === 'number' && !isNaN(selectedIndex)) {
if (selectedIndex >= 0 && selectedIndex < this.length) {
this._selectedIndex = selectedIndex;
} else {
this._selectedIndex = -1;
}
}
}
/**
* Returns item by index.
*
* @param index Index.
*/
public item(index: number): IHTMLOptionElement | IHTMLOptGroupElement {
return this[index];
}
/**
*
* @param element
* @param before
*/
public add(
element: IHTMLOptionElement | IHTMLOptGroupElement,
before?: number | IHTMLOptionElement | IHTMLOptGroupElement
): void {
if (!before && before !== 0) {
this._selectElement.appendChild(element);
return;
}
if (!Number.isNaN(Number(before))) {
if (before < 0) {
return;
}
this._selectElement.insertBefore(element, this[<number>before]);
return;
}
const index = this.indexOf(before);
if (index === -1) {
throw new DOMException(
"Failed to execute 'add' on 'DOMException': The node before which the new node is to be inserted is not a child of this node."
);
}
this._selectElement.insertBefore(element, this[index]);
}
/**
* Removes indexed element from collection.
*
* @param index Index.
*/
public remove(index: number): void {
if (this[index]) {
this._selectElement.removeChild(<IHTMLOptionElement>this[index]);
}
}
}