/
static.js
95 lines (76 loc) · 1.85 KB
/
static.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
/**
* Module dependencies
*/
var select = require('cheerio-select'),
parse = require('./parse'),
render = require('./render'),
decode = require('./utils').decode;
/**
* $.load(str)
*/
var load = exports.load = function(str, options) {
var Cheerio = require('./cheerio'),
root = parse(str, options);
var initialize = function(selector, context, r) {
return new Cheerio(selector, context, r || root);
};
// Add in the static methods
initialize.__proto__ = exports;
// Add in the root
initialize._root = root;
return initialize;
};
/**
* $.html([selector | dom])
*/
var html = exports.html = function(dom) {
if (dom) {
dom = (typeof dom === 'string') ? select(dom, this._root) : dom;
return render(dom);
} else if (this._root && this._root.children) {
return render(this._root.children);
} else {
return '';
}
};
/**
* $.text(dom)
*/
var text = exports.text = function(elems) {
if (!elems) return '';
var ret = '',
len = elems.length,
elem;
for (var i = 0; i < len; i ++) {
elem = elems[i];
if (elem.type === 'text') ret += decode(elem.data);
else if (elem.children && elem.type !== 'comment') {
ret += text(elem.children);
}
}
return ret;
};
/**
* $.root()
*/
var root = exports.root = function() {
return this(this._root);
};
/**
* $.contains()
*/
var contains = exports.contains = function(container, contained) {
// According to the jQuery API, an element does not "contain" itself
if (contained === container) {
return false;
}
// Step up the descendents, stopping when the root element is reached
// (signaled by `.parent` returning a reference to the same object)
while (contained && contained !== contained.parent) {
contained = contained.parent;
if (contained === container) {
return true;
}
}
return false;
};