0

Is there any method by which I can get url inside <img> tag from a link.

Eg: When I give a link of website, like a website or facebook page, I want to get all urls inside all the img tags in that site --> <*img src="url">

8
  • 3
    Have you tried anything yet that you can show us? Commented Sep 16, 2021 at 14:17
  • Does this answer your question? How to get URL of an image in JavaScript? Commented Sep 16, 2021 at 14:18
  • @Tushar No Bro nothing :( Commented Sep 16, 2021 at 14:18
  • stackoverflow.com/questions/5809051/… Commented Sep 16, 2021 at 14:20
  • 1
    Note that img src isn't always a URL Commented Sep 16, 2021 at 14:22

2 Answers 2

1

First send a request to a page, get the content and parse it to html. Then get all img tags by using getElementsByTagName method.

For example, if you want to get all img tags on https://jsonplaceholder.typicode.com, your code should be like below.

fetch('https://jsonplaceholder.typicode.com').then(function (response) {
    // The API call was successful!
    return response.text();
}).then(function (html) {

    // Convert the HTML string into a document object
    var parser = new DOMParser();
    var doc = parser.parseFromString(html, 'text/html');
    var imgTags = doc.getElementsByTagName("img");
    console.log(imgTags);
    
    var imgTagArr = [...imgTags];
    imgTagArr.forEach(img => console.log(img.src)); //iterate the all img tag srcs
}).catch(function (err) {
    // There was an error
    console.warn('Something went wrong.', err);
});

Example output:

json

Sign up to request clarification or add additional context in comments.

8 Comments

Let me test it now,I think it should work,I want something like this.Plan in my mind is like this
Bro Iam getting an error in console like Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at google.com. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
How can I overcome that Error
@Scania_16, Google's server might block your request. You can try it with another url, like jsonplaceholder.typicode.com. I updated the answer, just copy and paste it in console and see the output (like in screenshot below).
Bro That worked fine,But My actual aim was @ Facebook page,it didn't work it's till showing that same Same origin policy error
|
0

Yup , in Html like <img class="pqr" url ="xxxxxxx-yyy"/>
in Js file:

const img =document.querySelector('.pqr')
img.src // <-- this will give the src of the image 

2 Comments

No Bro,It Didn't Worked
I read the all comments . And i realized it is happen because of they setup CORS in their server that's way it happening

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.