I am using jsdom with jquery and it works fine. However, I try to modify my code a bit, so I don’t repeat it myself, so I made the main function from some jsdom code that accepts some html (DOM), improves it with jquery and spits it back, However, I cannot return my result and thus assign it to the var call. I probably won’t return to the right place, but I just don’t see the obvious, if so. May help a bit.
Here is the code:
function tweakIt(html_in){ var jsdom = require('jsdom'); jsdom.env({ html: html_in, scripts: [ '../public/javascripts/jquery-1.7.1.min.js', ], done: function(errors, window) { var $ = window.$; // do some jquery magic and manipulate the dom $('body').append('<div>foo</div>'); console.log('Freshly Manipulated HTML: '+ $('body').html()); // it logs perfectly return $('body').html(); // this isn't returned to where I called tweakIt() from, why not? } }); } var oldhtml = '<html><body><div>some text</div></body></html>'; var newhtml = tweakIt(oldhtml); // never gets set because nothing gets returned, why?
EDIT:
This was an async problem, so here's how to do it using a callback instead of returning:
function tweakIt(html_in, callback){ var jsdom = require('jsdom'); jsdom.env({ html: html_in, scripts: [ '../public/javascripts/jquery-1.7.1.min.js', ], done: function(errors, window) { var $ = window.$; // do some jquery magic and manipulate the dom $('body').append('<div>foo</div>'); console.log('Freshly Manipulated HTML: '+ $('body').html()); // it logs perfectly callback($('body').html()); // instead of a return, pass the results to the callback } }); } var oldhtml = '<html><body><div>some text</div></body></html>'; var newhtml = tweakIt(oldhtml, function(newstuff){ console.log(newstuff); // woohoo! it works! });
source share