2015-09-05 34 views
4

我有類似這樣查找和使用cheerio

<div class="form-row"> 
    <input type="text" id="foo1"> 
</div> 
<div class="form-row"> 
<input type="text" id="foo2"> 
</div> 
<div class="form-row"> 
    <input type="text" id="foo3"> 
</div> 

一個HTML片段替換某些屬性,我想用cheerio的ID標籤更改爲foobar的[1,2,3]

我代碼是

var cheerio = require("cheerio"); 
var $ = cheerio.load("html as above"); 

var inputs = $('input[id]'); 

Object.keys(inputs).forEach(function(key,index) { 
    if (key == index) { 
    console.log(key,inputs[key]) 
    //#1 
}); 

在這一點上(//#1),我想獲得的id屬性的值,並且根據在https://github.com/cheeriojs/cheerio的文檔我可以使用。數據方法獲取並改變屬性在el EMENT,但

inputs[key].data("id") 

給了我一個「類型錯誤:未定義是不是一個函數」錯誤

我知道我失去了一些東西簡單,但看不到樹木,不見森林,並希望一些指針。

感謝

更新#1

當我以爲我已經有了這樣的抓地力,它從我的指間溜走..

現在

,我想移動一個元素:

我有

<label>xyz<i class="fa fa-list"></i></label> 

,我想

<label>xyz</label><i class="fa fa-list"></i> 

代碼 - 不工作;) - 這是

var icons = $('label i'); 

icons.each(function(index,icon) { 
    // #2 now that I've got an element what now ? 
} 

我知道icons.remove()會刪除元素(一個或多個),但掙扎讓他們加入正確的地方。

回答

3

的問題是inputs[key])將是一個DOM元素的參考,這將不會有像data()

嘗試方法來設置像

var cheerio = require("cheerio"); 
var $ = cheerio.load('<div class="form-row">\ 
    <input type="text" id="foo1">\ 
</div>\ 
<div class="form-row">\ 
<input type="text" id="foo2">\ 
</div>\ 
<div class="form-row">\ 
    <input type="text" id="foo3">\ 
</div>'); 

var inputs = $('input[id]'); 

inputs.attr('id', function(i, id){ 
    return id.replace('foo', 'foobar') 
}); 

console.log($.html()) 
+0

微米的屬性值,哇,很好,工作 - 不能完全肯定或者爲什麼,但至少我有一些東西要看和理解;)謝謝。 – jmls

+0

我可以問另一個問題:我會使用類似的技術來重命名一個屬性,還是更好地添加和刪除?無論哪種方式,如何用這種技術來完成? – jmls

+0

@jmls你不能重命名一個屬性...你可以刪除並添加另一個 –