从html字符串获取img元素

时间:2014-07-29 14:35:20

标签: javascript jquery html html-parsing

我有以下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和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] 

2 个答案:

答案 0 :(得分: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 );

要获得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才能做到。

答案 1 :(得分:0)

这样做:

var image = $("img").html();