【问题标题】:find and replace certain attributes using cheerio使用cheerio查找和替换某些属性
【发布时间】: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


    【解决方案1】:

    问题是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())
    

    【讨论】:

    • 嗯,哇,效果很好 - 不完全确定或为什么,但至少我有一些东西要查看和理解;)谢谢。
    • 我可以问另一个问题:我会使用类似的技术来重命名属性,还是添加和删除更好?无论哪种方式,这种技术如何实现?
    • @jmls 您无法重命名属性...您可以删除并添加另一个
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多