Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue with .root() on CheerioAPI object #4139

Closed
doge247 opened this issue Oct 11, 2024 · 3 comments · Fixed by #4320
Closed

Issue with .root() on CheerioAPI object #4139

doge247 opened this issue Oct 11, 2024 · 3 comments · Fixed by #4320

Comments

@doge247
Copy link

doge247 commented Oct 11, 2024

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>'
@alokranjan609
Copy link

@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 element-and then apply append() or prepend() on it.

@doge247
Copy link
Author

doge247 commented Oct 17, 2024

Even then, this is pretty janky n stuff,
Leme see an example of wutcha mean @alokranjan609

@fb55
Copy link
Member

fb55 commented Dec 25, 2024

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging a pull request may close this issue.

6 participants
@fb55 @doge247 @alokranjan609 and others