Trying to select a 'body' tag from html that is returned by get() request

后端 未结 2 1042
醉梦人生
醉梦人生 2020-12-21 02:26

I\'m making an ajax get call that returns me contents of html page. I\'m trying to select contents of the body tag but my selector returns an empty jquery objec

2条回答
  •  时光说笑
    2020-12-21 03:09

    jQuery cannot select body of the response string, because the tag disappears when the string is converted using $().

    Hence, you have to select the body from the data string in another way, such as Regular expressions. Example:

    $.get(filename, function(data) {
        var body = data.replace(/^[\S\s]*]*?>/i, "")
                        .replace(/<\/body[\S\s]*$/i, "");
        //Optionally, convert the string to a jQuery object:
        body = $(body);
        console.log(body);
    }))
    

    Note: My Regular Expression assumed a wellformed HTML document, where > are correctly shown using HTML entities. If this is not the case, more advanced RegExps has to be used, such as the ones shown at this question.

提交回复
热议问题