I got an html page through an AJAX request
$.ajax({
async: true,
method: 'GET',
url: linkPage,
// cache: true,
success: function (data) {
console.log(data);
}
});
The data format I get like this:
<!DOCTYPE html>
<html>
<head>
...
</head>
<body id="sustainable" class='sustainable'>
<div id="wrap">
<main class="temp>
<section class="sec01">
...
</section>
</main>
</div>
</body>
</html>
Now I want to get the body id and class (which is “sustainable”) via this code:
$(data).find('body').attr('class');
But I have no idea why I can’t get that, it returns undefiend. But when I get html content or class of <main>
by this code:
$(data).find('main').attr('class');
$(data).find('main').html();
It returns exactly what I want. Can anybody explain me why?
I’ve tried some solutions so far by create a virtual DOM like this, and I can select <body>
and <main>
from AJAX data as I want: Cannot get body element from ajax response
But I still wonder why I can’t select <body>
class and html as first case?
3
Answers
The following jQuery Won’t work:
as the divs are top level elements and data isn’t an element but a string, to make it work you need to use .filter
It looks like, when given a string like that, jQuery will only save the contents of the body into its collection:
(Check your browser console. It’s selecting the text nodes around
#wrap
, and#wrap
itself, but not the<head>
or<body>
)You could use DOMParser instead, which will try to turn the whole string into a document, without trying to leave things out:
Another benefit of using DOMParser is that, unlike jQuery, it won’t execute possibly-unsafe code in the HTML string:
The reason it doesn’t work the way you tried is explained in the jQuery documentation:
Since you can’t have a
<body>
inside a<div>
, the browser ignores the<body>
tag.The documentation goes on to say: