Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract image url from HTML code using Javascript

Tags:

javascript

I am pulling information from a Page note from the Facebook API. In the output I get an image URL embeded in HTML code. How can I extract the image url from the HTML code below using Javascript?

<img class=\"photo_img img\" src=\"http://photos-c.ak.fbcdn.net/hphotos-ak-ash4/373909_207177302696060_189175211162936_438410_6588114253_a.jpg\" alt=\"\" />

UPDATE

The above image tag is embedded in the JSON-response from the Facebook API. I am also using Appcelerator to create an iOS app.

UPDATE 2

I solved it with:

json.data[i].message.match(/src=(.+?[\.jpg|\.gif|\.png]")/)[1]

Thankful for all help!

like image 295
Jonathan Clark Avatar asked Dec 19 '11 08:12

Jonathan Clark


People also ask

How do you link an image in Javascript?

createElement('a'); // setting the src attribute to the (hopefully) valid URI from above img. src = src; // setting the href attribute to the (hopefully) valid URI from above a. href = href; // appending the 'img' to the 'a' a. appendChild(img); // inserting the 'a' element *after* the 'form' element parent.


3 Answers

You can use jQuery to extract any data from html. Use the following code

$(function() {
  $('img').attr("src");
});

This will return you the src value only for the first instance of the img tag. If you want a specific img tag, you can include it inside a div.

like image 143
rdsoze Avatar answered Dec 30 '22 01:12

rdsoze


Ofcourse you can pull out these data using DOM. But question is is how many img tags would be there? or can you give some id's for this tags?

return document.getElementById(id).src; will do it, if it has an id.

or else, you might need to take the img tag array using getElementsByTagname('img')

If its a single img tag, then its easy with this. You can go for a second level class matching also.

like image 23
Kris Avatar answered Dec 29 '22 23:12

Kris


You can use code like this

var imgObj = document.getElementsByTagName('img')[0];
alert(imgObj.getAttribute('src'));

Update

If you are able to use jQuery, you can do the following

// select all images with the class 'photo_img'
var elements = $('img .photo_img').attr('src');

You could iterate through elements with a loop or jQuery's each function.

like image 33
Grrbrr404 Avatar answered Dec 29 '22 23:12

Grrbrr404