如何更改和检索HTML文档

我在NodeJS中使用JQuery npm来尝试处理一些HTML。 但我似乎无法得到最终的HTML文本发送与http模块的pipe道。 我可以得到$html.find('head')来产生HTML文本,但$html.find('html')和所有其他解决scheme产生一个对象。

这是我的代码:

 // 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()); 

http://jsfiddle.net/Wb7yV/4/

谢谢!

你非常接近你的jsfiddle。 要改变头部,只需使用这个:

 $('head').html('<title>with this</title>'); 

当您查看$html上的控制台日志时,您会注意到它包含2个索引对象: titletext 。 在查看这些对象的同时,请注意,没有任何子对象,例如jQuery.find()这样的函数是用来浏览的。

说明:获取当前匹配元素集中每个元素的后代,由select器,jQuery对象或元素过滤。

“标题”或“文本” filter将允许您根据需要select单个元素。

 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" 

严格执行你发布的内容,你可以看到$html是一个包含两个条目的Object数组。 如果你运行var res = $html[1]; console.log(res.textContent); var res = $html[1]; console.log(res.textContent); ,你可以得到正文的文字。 但不知道这是你之后?