blackhawk blackhawk - 1 month ago 14
jQuery Question

jQuery - Get the first image from parsed xml feed (content:encoded)

I am able to search through an XML feed with the following code

$($xml).find('item').each(function(i, e) { ... }


For each item within this loop, I am able to access my content:encoded element with the following lines and see the results...

$mcontent = $(this).find('encoded').text();
console.log('source: ' + $mcontent.match(/<img[^>]*>/g));


...which contains multiple images separated by commas like this...

<p><img src="...">, <img src="...">, <img src="..."></p>


How can I get the first image element only, and store than into an $mImage variable?

Thanks!

Update:

When I try to do the following...

$mcontent = $(this).find('encoded').text();
$mcontent = $mcontent.match(/<img[^>]*>/g).split(',')[0];
console.log('source: ' + $mcontent);


The browser tells me that...

Uncaught TypeError: $mcontent.match(...).split is not a function


..and I don't know why...

Answer

If your text is:

<p><img src="...">, <img src="...">, <img src="..."></p>

you may use:

var str = '<p><img src="...">, <img src="...">, <img src="..."></p>';
var firstImg = $($.parseHTML(str)[0]).find('img:first');

Uncaught TypeError: $mcontent.match(...).split is not a function

This happens because "$mcontent.match(/]>/g)"* returns an array of img and it's enough you get the first ele:

The snippet:

var str = '<p><img src="...">, <img src="...">, <img src="..."></p>';
var firstImg = $($.parseHTML(str)[0]).find('img:first');

console.log(firstImg[0].outerHTML);



var t = str.match(/<img[^>]*>/g)[0];

console.log(t);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Comments