-
Notifications
You must be signed in to change notification settings - Fork 0
/
dom.js
105 lines (83 loc) · 2.6 KB
/
dom.js
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
/* Basic DOM methods */
var Node = function(type) {
this.type = type; // 'element' or 'text'
this.parent = {};
};
var Text = exports.Text = function(text) {
Node.call(this, 'text');
this.text = text;
};
var Element = exports.Element = function(name, attributes) {
Node.call(this, 'element');
this.name = name || '';
this.attributes = attributes || '';
this.children = [];
};
Text.prototype = Object.create(Node.prototype);
Element.prototype = Object.create(Node.prototype);
Node.prototype.__defineGetter__('textContent', function() {
var text = '';
if (this.type == 'text') {
return this.text;
}
for (var i = 0; i < this.children.length; i++) {
text += this.children[i].textContent;
}
return text;
});
Element.prototype.getElementsBy = function(test) {
// test: element -> bool
// recursively filter element's children by test
var elems = [], children = this.children;
for (var i = 0; i < children.length; i++) {
if (children[i].type != 'element') {
continue;
}
if (test(children[i]) === true) {
elems[elems.length] = children[i];
}
if (children[i].children.length > 0) {
elems = elems.concat(children[i].getElementsBy(test));
}
}
return elems;
};
Element.prototype.getElementBy = function(test) {
// test: element -> bool
// equivalent to getElementsBy(test)[0]
var elem, children = this.children;
for (var i = 0; i < children.length; i++) {
if (children[i].type != 'element') {
continue;
}
if (test(children[i]) === true) {
return children[i];
}
if (children[i].children.length > 0 &&
(elem = children[i].getElementBy(test), elem !== void 0)) {
return elem;
}
}
return void 0;
};
Element.prototype.getElementById = function(id) {
return this.getElementBy(function(elem) {
return elem.attributes.id ? elem.attributes.id == id : false;
});
};
Element.prototype.getElementsByName = function(name) {
return this.getElementsBy(function(elem) {
return elem.attributes.name ? elem.attributes.name == name : false;
});
};
Element.prototype.getElementsByClassName = function(name) {
return this.getElementsBy(function(elem) {
return elem.attributes['class'] ?
elem.attributes['class'].split(' ').indexOf(name) != -1 : false;
});
};
Element.prototype.getElementsByTagName = function(name) {
return this.getElementsBy(function(elem) {
return elem.name == name;
});
};