我有以下html字符串:
<html>
<head>
</head>
<body>
<table>
<tbody>
<th>
<tr>
<img src=""/>
</tr>
</th>
</tbody>
</table>
</body>
</html>
有没有办法只获取
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 );
}
wikiHTML是我以json格式对Wikipedia API提出的几个搜索词的请求。
编辑:
从img和信息框返回:
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]
最佳答案
是的,例如在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 );
要获取
img
html代码,您将需要:console.log( img[0].outerHTML )
编辑
因此,根据您的编辑,您的代码应为:
$wikiDOM = $("<document>"+ wikiHTML+ "</document>");
var infobox = $( $wikiDOM.find('.infobox').html() );
if(infobox != 'undefined' && infobox !== ""){
var img = infobox.filter( 'img' );
console.log( img[0].outerHTML );
}
如您所见,我在
$()
周围添加了$wikiDOM.find('.infobox').html()
。之所以得到undefined
,是因为innerHTML
DOM属性没有filter
方法。只有jQuery可以。