Reputation: 4411
I need to get the class attribute from the body element of a page object retrieved with $.get(). In my example below, fullContent is set to the object but I can't select the body element... I'd rather not resort to text manipulation to get this
$.get(url, refreshFullContent);
var refreshFullContent = function(response, status, xhr)
{
fullContent = response;
var bodyclass = $(fullContent).find("body").attr("class");
$("body").attr("class", bodyclass);
}
Is there a way to get this with selectors on the object (like I'm trying to do in this example)? If not, what is the best way to get this from the text? xhr.responseText contains the string of the entire response.
Upvotes: 2
Views: 14850
Reputation: 4357
i tried the solution of user113716, but unfortunatly, body class was always undefined. but this solution works for me:
$("body").attr("class", data.match(/body class=\"(.*?)\"/)[1]);
while data is my ajax response and body has to look like this:
<body class="classname...">
means right after the body element comes the class attribute (or you have to rewrite the regex).
Upvotes: 2
Reputation: 33408
$("a").click(function (e) {
e.preventDefault();
$.get(this.pathname, function(response) {
var $dom = $(document.createElement("html"));
$dom[0].innerHTML = response; // Here's where the "magic" happens
var $body = $(dom).find("body");
// Now you can access $body as jquery-object
// $body.attr("class");
});
});
Upvotes: 1
Reputation: 31
Here is a solution to get the body class from $.get
.
$.get(url, refreshFullContent);
var refreshFullContent = function(response, status, xhr)
{
$("body").attr("class", /body([^>]*)class=(["']+)([^"']*)(["']+)/gi.exec(response.substring(response.indexOf("<body"), response.indexOf("</body>") + 7))[3]);
}
Upvotes: 3
Reputation: 322502
If you're getting a full HTML document response, you won't get consistent behavior between browsers.
Some browsers will strip away the head
and body
elements.
You could try this, but no guarantees:
var fullContent = '<div>' + response + '</div>';
var bodyclass = $(fullContent).find("body").attr("class");
$("body").attr("class", bodyclass);
Upvotes: 3