I got an html page through an AJAX request
$.ajax({
async: true,
method: \'GET\',
url: linkPage,
// cache: true,
success: function (data) {
It looks like, when given a string like that, jQuery will only save the contents of the body into its collection:
const data = `
...
...
`;
console.log($(data)[0]);
console.log($(data)[1]);
console.log($(data)[2]);
(Check your browser console. It's selecting the text nodes around #wrap
, and #wrap
itself, but not the or
)
You could use DOMParser instead, which will try to turn the whole string into a document, without trying to leave things out:
const data = `
...
...
`;
const doc = new DOMParser().parseFromString(data, 'text/html');
console.log(doc.body.className);
Another benefit of using DOMParser is that, unlike jQuery, it won't execute possibly-unsafe code in the HTML string:
const data = `
...
`;
$(data);
jQuery version, unsafe
const data = `
...
`;
const doc = new DOMParser().parseFromString(data, 'text/html');
console.log(doc.body.className);
DOMParser version, safe