I have an HTML string that contains text and images, e.g.
<p>...</p>
<img src="..." />
<p>...</p>
I need to get the src attribute of the first image. The image may or may not come after a <p>
and there could be more than one image, or no image at all.
Initially, I tried appending the string to the DOM and filtering. But, if I do this the browser requests all of the external resources. In my situation, this adds a lot of unnecessary overhead.
My initial approach:
var holder = $('<div></div>');
holder.html(content);
var src = holder.find('img:first').attr('src');
How can I get the src of the first image without appending the HTML? Do I need to use a regular expression, or is there a better way?
The solution needs to be javascript/jQuery based – I'm not using any server side languages.
My question is very similar to: http://forum.jquery.com/topic/parsing-html-without-retrieving-external-resources
Thanks
content
in your code ? – user372551 Sep 14 '10 at 19:18content
refers to the HTML string. The HTML string describes a news article – it could contain text, images or videos. The string comes from a JSON object, e.g. var content = myJSONObj.articleText; where the value could be something like:Some text...<img src="http://..." border="0" alt="My alt text"><br>More text...
– DB. Sep 15 '10 at 2:21