raeq
raeq

Reputation: 971

How to grab an image tag from html via jquery

So I have a data set that is returning something like this in the variable entry.content:

<p style="float:right;margin:0 0 10px 15px;width:240px"> <img src="http://citysportsblog.com/wp-content/uploads/2011/09/RagnarNE.jpg" width="240"> </p><p>Have you heard of the epic adventure that is the</p>

How would i just grab the img src url from this via jquery?

Upvotes: 0

Views: 374

Answers (4)

Shawn Mclean
Shawn Mclean

Reputation: 57469

You should give your image an Id and use the id selector (that way you know its only that element you're getting). You can run query code on plain text (not added to the DOM) as follows:

string plainText = '<p style="float:right;margin:0 0 10px 15px;width:240px"> <img id="theImg" src="http://citysportsblog.com/wp-content/uploads/2011/09/RagnarNE.jpg" width="240"> </p><p>Have you heard of the epic adventure that is the</p>'

var url = $(plainText).find('#theImg').attr('src');

Or if you cant modify it and its just that one image thats in the string:

var url = $(plainText).find('img').attr('src');

Upvotes: 0

Waleed Khan
Waleed Khan

Reputation: 11467

If it were me, I'd just regex replace to get the source from the variable:

entry.content = entry.content.replace("/src=\"(.+?)\"/i", "\1");

(although you wouldn't want to use .+; I was just too lazy to find the possible URL characters). If you're not sure if entry.content will be in that form, then I'd add it to the DOM in a hidden div and get the source from there:

var hiddenDiv = $(document.body).add("div");
hiddenDiv.css("display", "none");
hiddenDiv.html(entry.content);
entry.content = hiddenDiv.find("img")[0].src;

Granted, that's a far more dangerous approach, as it leaves you open to XSS, but if you trust the source, you could do it.

Upvotes: 0

Maverick
Maverick

Reputation: 3059

If you don't have any other images with the same size:

$('img[width="240"]').attr('src');

Upvotes: 0

zzzzBov
zzzzBov

Reputation: 179046

assuming you only have one image: var sourceUrl = $('img').attr('src');

var sourceUrl = $(entry.content).find('img').attr('src');

Upvotes: 2

Related Questions