I'm using JQuery npm within NodeJS to try to process some HTML. But I can't seem to get the final html as text to send down the pipe with the http module. I can get $html.find('head') to yield html text, but $html.find('html') and all other solutions yield an object.
Here's my code:
// this code, which will run under nodejs using jquery, should update the head in an entire html document
var $ = require('jquery');
var $html = $('<html><head><title>this should be replaced</title></head><body>and the entire document should be available as text</body></html>');
console.log('html', $html);
var $body = $html.find('body');
var res = $html.find('head').replaceWith('<head><title>with this</title></head>');
console.log(res.html());
thanks!
When you view the console log on $html you'll notice it contains 2 indexed objects: title and text. While viewing those objects, notice that neither have any children, which functions such as jQuery.find() are designed to browse.
Description: Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.
A filter for 'title' or 'text' will allow you to select the individual elements as needed.
var $html = $('<html><head><title>this should be replaced</title></head><body>and the entire document should be available as text</body></html>');
var $title = $html.filter('title');
var $body = $html.filter('text');
var res = $title.html('replace with this');
console.log(res.filter('title').html());
// returns: "replace with this"
You're pretty close with your jsfiddle. To change the head, just use this:
$('head').html('<title>with this</title>');
Going strictly with what you've posted, you can see $html is an Object array with two entires. If you run var res = $html[1];
console.log(res.textContent);, you can get the text of the body. But not sure if this is what you're after?