João
João

Reputation: 341

Getting img element from html string

I have the following html string:

<html>
<head>
</head>
<body>
    <table>
        <tbody>
            <th>
              <tr>
                <img src=""/>
              </tr>
            </th>
        </tbody>
    </table>
</body>
</html>

Is there a way to get only the img element?

So in this case I want a string like this <img src=""/>.

More specific example:

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

where wikiHTML is the request i make to wikipedia api in json format for several searchterms.

Edit:

return from img and 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] 

Upvotes: 0

Views: 3457

Answers (2)

antyrat
antyrat

Reputation: 27765

Yes, for example in jQuery you will need to pass your string to $ function and then get <img> by img selector:

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 );

To get img html code you will need:

console.log( img[0].outerHTML )

EDIT So according to your edit your code should be:

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

As you can see I have added $() around $wikiDOM.find('.infobox').html(). You were getting undefined because innerHTML DOM property doesn't have filter method. Only jQuery do.

Upvotes: 6

Bla...
Bla...

Reputation: 7288

This would do:

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

Upvotes: 0

Related Questions