skip to Main Content

I have a page that uses the jQuery one liner

$('#id').load('/url');

to load a fragment into the DOM at a specific place.

If I want to remove the dependency on jQuery, is there an easy alternative way to do this โ€” possibly with the relatively new fetch() API?

3

Answers


  1. You can do like this:

    fetch('/method')
    .then(response=> response.text())
    .then(res => { document.getElementById('id').innerHTML = res; });
    
    Login or Signup to reply.
  2. Do it like so:

    fetch('/url')
      .then(response => response.text())
      .then(value => {
        document.getElementById('id').innerHTML = value
      });
    
    Login or Signup to reply.
  3. Almost a one liner ๐Ÿ™‚

    ;(async () => {
        document.getElementById('id').innerHTML = await (await fetch('/url')).text();
    })();
    

    to put it to some practical use you’d have at least to check the response code, so I’d first refactor it like this

    ;(async () => {
        let res = await fetch('/url');
        if(res.ok){
            document.getElementById('id').innerHTML = await res.text();   
        }
        else { ... }
    })();
    

    error handling is still missing, but I’m sure you get the picture ๐Ÿ™‚

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search