从html字符串获取img元素

Joã*_*oão 0 html javascript jquery html-parsing

我有以下html字符串:

<html>
<head>
</head>
<body>
    <table>
        <tbody>
            <th>
              <tr>
                <img src=""/>
              </tr>
            </th>
        </tbody>
    </table>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

有没有办法只获得img元素?

所以在这种情况下我想要一个像这样的字符串<img src=""/>.

更具体的例子:

$wikiDOM = $("<document>"+ wikiHTML+ "</document>");
var infobox = $wikiDOM.find('.infobox').html();
if(infobox != 'undefined' && infobox !== ""){
    var img = infobox.filter( 'img' );
    console.log( img[0].outerHTML );
}
Run Code Online (Sandbox Code Playgroud)

其中wikiHTML是我对json格式的wikipedia api的请求,用于几个searchterms.

编辑:

从img和infobox返回:

image:[object Object] 
infobox[object Object] 
image:[object Object] 
infobox[object Object]
image:[object Object] 
infobox[object Object]
image:[object Object] 
infobox[object Object] 
image:[object Object] 
infobox[object Object]
image:[object Object] 
infobox[object Object]
image:[object Object] 
infobox[object Object] 
image:[object Object] 
infobox[object Object] 
Run Code Online (Sandbox Code Playgroud)

ant*_*rat 5

是的,例如在jQuery中,您需要将字符串传递给$函数,然后<img>通过img选择器获取:

var html = $( '<html><head></head><body><table><tbody><th><tr><img src=""/></tr></th></tbody></table></body></html>' )
var img = html.filter( 'img' );
console.log( img );
Run Code Online (Sandbox Code Playgroud)

要获得imgHTML代码,您将需要:

console.log( img[0].outerHTML )
Run Code Online (Sandbox Code Playgroud)

编辑 所以根据您的编辑,您的代码应该是:

$wikiDOM = $("<document>"+ wikiHTML+ "</document>");
var infobox = $( $wikiDOM.find('.infobox').html() );
if(infobox != 'undefined' && infobox !== ""){
    var img = infobox.filter( 'img' );
    console.log( img[0].outerHTML );
}
Run Code Online (Sandbox Code Playgroud)

如你所见,我已经添加$()$wikiDOM.find('.infobox').html().你得到了undefined因为innerHTMLDOM属性没有filter方法.只有jQuery这样做.