...">

Find and replace specific attributes with cheerio

I have a html fragment similar to this

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

and I wanted to use cheerio to change the id foobar tag [1,2,3]

my code

 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
 });

at this point (// # 1), I wanted to get the id attribute value and according to the docs https://github.com/cheeriojs/cheerio I can use the .data method to get and change the attribute in the element, but

inputs[key].data("id")

gives me "Error TypeError: undefined is not a function"

I know that I missed something simple, but I don’t see a tree for trees and I appreciate some pointers.

thanks

update # 1

as soon as I think I have enough for it, it slips out of my fingers.

Now, I want to move the item:

I have

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

I want too

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

code - which does not work;) is

var icons = $('label i');

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

, icons.remove() , .

+4
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())
+3

Source: https://habr.com/ru/post/1606041/


All Articles