【发布时间】:2015-12-01 09:21:51
【问题描述】:
我有一个类似的html片段
<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>
我想用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 的文档,我可以使用 .data 方法来获取和更改元素中的属性,但是
inputs[key].data("id")
给我一个“TypeError: undefined is not a function”错误
我知道我遗漏了一些简单的东西,但看不到树木的树木,希望得到一些指点。
谢谢
更新 #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() 会删除元素,但很难将它们添加到正确的位置。
【问题讨论】:
标签: javascript html-parsing cheerio