2013-03-13 86 views
2

我在NodeJS中使用JQuery npm嘗試處理某些HTML。但我似乎無法得到最終的HTML作爲文本發送與http模塊的管道。我可以得到$html.find('head')以生成html文本,但$html.find('html')和所有其他解決方案產生一個對象。如何更改和檢索HTML文檔

這裏是我的代碼:

// 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/

的感謝!

+0

順便說一句,'$ html.find('head')'不會產生任何HTML文本。 – 2013-03-13 19:27:52

回答

0

當您查看控制檯日誌$html時,您會注意到它包含2個索引對象:titletext。在查看這些對象時,請注意,既沒有任何子女,設計了哪些功能(如jQuery.find())可供瀏覽。

描述:獲取當前匹配的元素集合中的每個元件中,通過選擇器,jQuery對象,或元件過濾的後代。

對於「標題」或「文本」,您可以根據需要選擇單個元素。

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" 
+0

謝謝,但我的目標不是取代已經有效的標題。我的目標是在做一些替換之後檢索html文本。 – davidm 2013-03-13 19:31:03

+0

@davidm,這樣做的方式和你做的一樣,但是因爲你沒有任何DOM後代,所以你不能在你創建的字符串中使用'find'。但是,您仍然可以在替換文本之前和之後選擇它們。只需使用'filter'並查看'console.log(object)'來查看可以過濾哪些節點。 – 2013-03-13 19:49:00

+0

@davidm,我編輯了代碼來演示它如何工作。 – 2013-03-13 20:02:11

0

你和你的jsfiddle很接近。 要改變頭,只要使用此:

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

與您發佈什麼去嚴格,你可以看到$html是一個對象數組有兩個entires。如果您運行var res = $html[1]; console.log(res.textContent);,您可以獲取正文的文本。但不知道這是你的追求?