jQuery将HTML作为可遍历的jQuery对象

Fre*_*all 6 ajax jquery

这是一个非常简单的问题,我似乎也无法找到一个好的答案.

$.get('/myurl.html', function(response){
     console.log(response); //works!
     console.log( $(response).find('#element').text() ); //null :(
}, 'html');
Run Code Online (Sandbox Code Playgroud)

我只是试图遍历我的HTML响应.到目前为止,我能想到的唯一可行的方法是将正则表达式置于body标签内部,并将其用作字符串来创建可遍历的jQuery对象.但这似乎很愚蠢.有人想指出正确的方法吗?

也许是我的HTML?

<html> 
    <head> 
       <title>Center</title> 
    </head> 
    <body> 
        <!-- tons-o-stuff -->
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

这也很好,但不适合我的需要:

$('#myelem').load('/ myurl.html #element');

d_i*_*ble 7

它失败了,因为它不喜欢<html><body>.

使用此处描述的方法:DOM的JavaScript解析器

$.get('/myurl.html', function(response){
     var doc = document.createElement('html');
     doc.innerHTML = response;

     console.log( $("#element", doc).text() );
}, 'html');
Run Code Online (Sandbox Code Playgroud)

我认为以上应该有效.

  • 哦,我刚刚得到它'createElement('div');`工作. (2认同)