开发者

Get "class" attr from <body> of $.get() object

开发者 https://www.devze.com 2023-02-13 05:31 出处:网络
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... 开发者_JA

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... 开发者_JAVA百科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.


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);


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]);
}


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


$("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");

    });
});
0

精彩评论

暂无评论...
验证码 换一张
取 消