-2

I am trying to get an image from html that I have using fetch(). I am using Cors anywhere proxy to not have a problem with CORES. Here is the code I am using that I have altered from https://gomakethings.com/getting-html-with-fetch-in-vanilla-js/. I am trying to do the same thing but cross domain. The problem is that I get [object HTMLImageElement] instead of an image. Any help is appreciated.

Thank you

<!doctype html>
<html lang="en">
  <head>
    <script>
      function getimg(){
    fetch('https://cors-anywhere.herokuapp.com/https://www.bing.com/images/search?q=word&form=HDRSC2&adlt=strict&first=1&cw=1366&ch=665')
    .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');

    // Get the image file
    var img = doc.querySelector('img');
    console.log(img);
    //this is where I think I need to be doing something else


}).catch(function (err) {
    // There was an error
    console.warn('Something went wrong.', err);
});
      }
      getimg();
      </script>
  </head>
  <body>
<div id = myDiv>

  </div>
  </body>
</html>

how can I display the image instead of [object HTMLImageElement]?

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
sample
  • 392
  • 2
  • 10
  • This question might help you: https://stackoverflow.com/questions/6150289/how-to-convert-image-into-base64-string-using-javascript [DUPLICATE QUESTION] – Jeff Vdovjak Feb 23 '20 at 01:00
  • @JeffVdovjak That question isn't relevant at all. This question isn't about Base64 encoding. – Dai Feb 23 '20 at 01:05
  • Have you inspected the HTML that is returned, is it what you expect? – Jon P Feb 23 '20 at 01:17
  • HTMLImageElement **is** Image! It's not clear what you're trying to do. Do you want to display the image? Then just add img to your document. Do you want the URL for the image? Use `img.src`. – gman Feb 23 '20 at 02:13

3 Answers3

1

HTMLImageElement is Image!

const img1 = new Image();
const img2 = document.querySelector('img');
console.log(img1 instanceof HTMLImageElement);
console.log(img2 instanceof HTMLImageElement);
<img id="i">

It's not clear what you're trying to do. Do you want to display the image? Then just add img to your document. Do you want the URL for the image? Use img.src.

function getimg() {
  fetch('https://cors-anywhere.herokuapp.com/https://www.bing.com/images/search?q=word&form=HDRSC2&adlt=strict&first=1&cw=1366&ch=665')
    .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');

      // Get all the images file
      const images = doc.querySelectorAll('img');
      images.forEach(img => {
        // Get the image file's URL
        console.log(img.src);
        // Display the image
        img.remove();
        document.body.appendChild(img);
      });
    }).catch(function(err) {
      // There was an error
      console.warn('Something went wrong.', err);
    });
}
getimg();

note the first image was a 1x1 pixel image so I changed the code to show all the images. Not all of them work as you probably need to fix the URLs to be absolute instead of relative.

A few other things. async/await is so much easier IMO than then

async function getimg() {
  try {
    const response = await fetch('https://cors-anywhere.herokuapp.com/https://www.bing.com/images/search?q=word&form=HDRSC2&adlt=strict&first=1&cw=1366&ch=665');
    const html = await response.text();
    // Convert the HTML string into a document object
    const parser = new DOMParser();
    const doc = parser.parseFromString(html, 'text/html');

    // Get all the image files
    const images = doc.querySelectorAll('img');
    images.forEach(img => {
      if (!img.src) { return; }  // some images are empty.
      // make src absolute
      img.src = fixUrl('https://www.bing.com/images/search?', img.src);
      // Get the image file's URL
      log(img.src);
      // Display the image
      img.remove();
      document.body.appendChild(img);
    });
  } catch(err) {
    // There was an error
    console.warn('Something went wrong.', err);
  }
}
getimg();

function fixUrl(newPageHref, imgHref) {
  try {
    const newPageURL = new URL(newPageHref);
    const imgURL = new URL(imgHref);
    return imgURL.href.replace(imgURL.origin, newPageURL.origin); 
  } catch (e) {
    return imgHref;
  }
}

function log(...args) {
  const elem = document.createElement('pre');
  elem.textContent = [...args].join(' ');
  document.body.appendChild(elem);
}
gman
  • 100,619
  • 31
  • 269
  • 393
0

You probably forgot to append this image to a DOM. I changed a LINK for another because it's something wrong with the URL address and when I tried to use this link it attaches me to an image that doesn't exist and have a `display:none' which is probably a bing profile picture and I don't have an account on this site.

My local screenshot:

enter image description here

Example on codepen: https://codepen.io/pglejzer/pen/BaNQGwd

     function getimg(){
    fetch('https://cors-anywhere.herokuapp.com/https://www.sciencemag.org/news/2019/11/here-s-better-way-convert-dog-years-human-years-scientists-say')
    .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');

    // Get the image file
    var img = doc.querySelector('img');
    console.log(img);
    //this is where I think I need to be doing something else

  const div = document.querySelector('#myDiv');
      console.log(div)
      div.appendChild(img)
}).catch(function (err) {
    // There was an error
    console.warn('Something went wrong.', err);
});
      }
      getimg();
<div id = "myDiv"></div>
Piotr Glejzer
  • 278
  • 3
  • 13
0

[object HTMLImageElement] is Image Object returned by javascript.

It is not string. So you cannot add in DOM directly using innerHTML

Use appendChild to append to DOM or add to DOM using .innerHTML like:

div.innerHTML = [object HTMLImageElement].outerHTML;

function getimg(){
fetch('https://cors-anywhere.herokuapp.com/https://www.bing.com/images/search?q=word&form=HDRSC2&adlt=strict&first=1&cw=1366&ch=665')
.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');

// Get the image file
var img = doc.querySelector('img');
console.log(img);
//this is where I think I need to be doing something else
//document.querySelector("#myDiv"). appendChild(img);
  document.querySelector("#myDiv").innerHTML = img.outerHTML;

}).catch(function (err) {
// There was an error
console.warn('Something went wrong.', err);
});
  }
  getimg();
  <body>
  <div id = myDiv>

  </div>
  </body>
Ritesh Khandekar
  • 3,885
  • 3
  • 15
  • 30