summaryrefslogtreecommitdiffstats
path: root/packages/gitbook-html/lib/dom.js
blob: d8f7c842139b2028718aab293e2c2836f0e97790 (plain)
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
var _ = require('lodash');
var cheerio = require('cheerio');

// Parse an HTML string and return its content
function parse(html) {
    var $ = cheerio.load(html);
    var $el = $('html, body').first();

    return $el.length > 0? $el : $;
}

// Return main element
function root($) {
    var $el = $('html, body, > div').first();
    return $el.length > 0? $el : $.root();
}

// Return text node of an element
function textNode($el) {
    return _.reduce($el.children, function(text, e) {
        if (e.type == 'text') text += e.data;
        return text;
    }, '');
}

// Cleanup a dom
// Remove all divs
function cleanup($el, $) {
    $el.find('div').each(function() {
        var $div = $(this);
        cleanup($div, $);

        $div.replaceWith($div.html());
    });

    return $el;
}

module.exports = {
    parse: parse,
    textNode: textNode,
    root: root,
    cleanup: cleanup
};