Issue with .root() on CheerioAPI object
It seems that cheerio cannot see the root element I've supplied and isn't wrapping the new element into the root as a result of that
const cheerio = require('cheerio');
const errorDoc = cheerio.load(`<error></error>`, { xml: true })
console.log(errorDoc.root().prop('outerHTML'));
// ^^^ First red flag as I'd expect it to return the <error /> element
errorDoc.root().prepend(`<message>yooo</message>`);
console.log(errorDoc.xml()); // '<message>yoo</message><error/>'
// ^^^ The real issue here
And with .append()
const cheerio = require('cheerio');
const errorDoc = cheerio.load(`<error></error>`, { xml: true })
console.log(errorDoc.root().prop('outerHTML'));
// ^^^ First red flag as I'd expect it to return the <error /> element
errorDoc.root().append(`<message>yooo</message>`);
console.log(errorDoc.xml()); // '<error/><message>yoo</message>'
@doge247 This is because root() does not work as you would expect in XML mode. Fix: Get directly the element you want to change-it is actually the
Even then, this is pretty janky n stuff, Leme see an example of wutcha mean @alokranjan609
.root() returns a document node, which contains all other nodes. This is the same for every kind of markup. I've added support for .prop calls on document nodes in #4320, which means it is now possible to get the outer HTML of the root node.
If you do want to append to a specific Node, you'll have to create a selection with that node first:
errorDoc.root().children().append(`<message>yooo</message>`); // appends to the first child
console.log(errorDoc.xml()); // '<error><message>yoo</message></error>'