How to correctly replace only a portion of a page without Jquery

Instead of replacing the whole page I need to replace only the div with id “example” with an html file instead of an html string. I know it can be done with jquery load but I want to avoid it. This is what I have so far…

if (screen.width >= 767 && CurrentPage != 'DesktopPage') {
        //return window.location.replace("desktop.php");
        document.getElementById('example').innerHTML = 'Your content';
    }

Windows location replaces the whole page, and innerHTMLl uses a string… :confused:

1 Like

I think the fetch method might work in this situation.

1 Like

Well, you could fetch(...) the php contents as a string, and use innerHTML with that string, or you could get the string, convert it to actual DOM in a variable, and then use appendChild to place it in your container.

Personally, i prefer the second approach, as i can work with that DOM variable in memory, attaching listeners or classes before injecting it.

How that whole “string to DOM” thing works took me a while to work out, but David Walsh has a great post about it: Convert String to DOM Nodes

1 Like

Great!! Thank you both!! Question can it be used like this?
document.getElementById('example').innerHTML = fetch('desktop.php');
I apologize I know is a very basic question just that JS is my weakness right now.

Edit I found another helpful guide : Tutorial de Fetch

No, fetch returns a Promise and thus has to be handled differently then a function that returns a simple value. The tutorial you linked to has a perfect example of how you would want to use fetch:

fetch('file-to-read.txt')
  .then( response => response.text() )
  .then( resultText => console.log(resultText) )
  .catch( err => console.log(err) );

Do you know what Promises are? How about arrow functions? If not then these examples might be a little hard to follow. In the second then you have the actual HTML string you are looking for (resultText) so you can then set innerHTML to that string there:

 .then( resultText => document.getElementById('example').innerHTML =resultText )
1 Like

In the second then you have the actual HTML string you are looking for ( resultText ) so you can then set innerHTML to that string there:

Thank you so much for the help !! :slight_smile:

I’m afraid I don’t know any of those concepts… o.o
Edit: Will look them up…

I have made some progress but is not working yet… sadly. May I ask some extra guidance? Current code:
by the way I applied to a Javascript course but I need to get this working for a new page…

<script type="text/javascript">
window.addEventListener("resize", getTemplate);

CurrentPage = 'MobilePage';

function getTemplate() {
    if (screen.width >= 767 && CurrentPage != 'DesktopPage') {        
        fetch('desktop.htm')
          .then(response => response.htm())
          .then( resultText => console.log(resultText) )
          .then( resultText => document.getElementById('example').innerHTML = resultText )
          return resultText;              
    }
    if (screen.width < 767 && CurrentPage != 'MobilePage') {
        //return window.location.replace("mobile.html");
        fetch('mobile.htm')
          .then(response => response.htm())
          .then( resultText => console.log(resultText) )
          .then( resultText => document.getElementById('example').innerHTML = resultText )
          return resultText; 
    }
}
getTemplate();
</script>

OK, a few things here:

  • .then(response => response.htm())

There is no method htm() on the response object. You want to use response.text() as shown in the example above. This line throws a TypeError.

  • .then( resultText => console.log(resultText) )

You can do this but then it will ruin what you want to do next because console.log doesn’t return the HTML string that you need to set innerHTML, and thus the next line will merely insert ‘undefined’ into your example element. So get rid of this line completely.

  • return resultText;

This is not returning the HTML string you fetched but rather undefined because the variable resultText is not in scope. But it won’t even get that far because this line will throw an Uncaught ReferenceError. You should get rid of it.

So then we are back to:

fetch('desktop.htm')
          .then(response => response.text())
          .then( resultText => document.getElementById('example').innerHTML = resultText );

This is the bare minimum that will do what you want. Change the mobile one to do the same thing.

1 Like

Thank youu :slight_smile: Roger!
I’m getting this error on the console:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///C:/Users/***/test/desktop.htm. (Reason: CORS request not http)

Well is not big deal as it just may mean I have to test it in a local server installation if I understood it correctly…

Edit: yes that was it, now that error is gone

There’s another though:

Uncaught (in promise) TypeError: response.txt is not a function

It’s response.text()

Oh my god, sorry. It works!!! :smiley:
Thank you for everything.