0

I'm trying to do a fetch request to example.com, and trying to get a specific ElementID from the fetched webpage into the console log without success.

I've tried the following code without success yet:

const url = "https://example.com"; 
fetch(url) 
  .then(response => response)
  .then(data => {
    const resData = data.text();
    console.log(resData);
    document.getElementById("id").innerHTML = resData;
  })
.catch((err) => console.log("Can’t access " + url + " response. Blocked by browser?" + err));

I'll be for your suggestions'. Thanks

I'm getting TypeError: Cannot set property 'innerHTML' of null

ChinChen
  • 13
  • 1
  • 4
  • `.then(response => response)` does nothing ... you need to return `response.text()` - since, `const resData = data.text();` results in `resData` being a Promise ... i.e. `fetch(url).then(response => response.text()).then(resData => {` – Jaromanda X Jun 26 '21 at 01:33
  • copy your html and the response you are getting from url. – Amit Verma Jun 26 '21 at 03:11

2 Answers2

0

Your issue is that your current document
does not contain an element wit the id "id" (document.getElementById("id")).
This results that this expression will evaluate to null which explains the error you're facing.

In your case I would suggest something like this:
Creating a new container where you can insert the HTML code and work with.
As reference: Creating a new DOM element from an HTML string using built-in DOM methods or Prototype

const url = "https://example.com"; 
fetch(url) 
  .then(data => {
    const resData = data.text();
    console.log(resData);

    const responseContainer = document.createElement("div");
    responseContainer.innerHTML = "";

    /* 
     * Work with the responseContainer.
     * As example to get all elements with class "example":
     * responseContainer.getElementsByClassName("example")
     */
  })
.catch((err) => console.log("Can’t access " + url + " response. Blocked by browser?" + err));
WolverinDEV
  • 1,494
  • 9
  • 19
0

An error you're getting simply shows that there is not such element on the page you're trying to fetch.

If you want to do that, make sure there is a div with that id and if it's not there make sure you make it before you send response.

  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 31 '22 at 01:32