Search code examples
javascriptnode.jsv8

node.js inspecting dom like standard javascript


How is it possible to create document object from html source and use document.* functions like getElementById in node.js?


Solution

  • If you just want to use a jQuery-like API to traverse and fiddle with HTML markup, a better option is cheerio.

    jsdom is a full-fledged DOM implementation that can even run the JS that comes with a page. As a result, it's pretty heavy. If you don't need any of that functionality, cheerio is 8x faster.

    var cheerio = require('cheerio'),
        $ = cheerio.load('<h2 class="title">Hello world</h2>');
    
    $('h2.title').text('Hello there!');
    $('h2').addClass('welcome');
    
    $.html();
    //=> <h2 class="title welcome">Hello there!</h2>