Marissa
Marissa

Reputation: 23

Get HTML From Another File Using Javascript

I have a collection of buttons and when I click them I am trying to display the HTML from a different file. I tried dabbling in JQuery but I decided I want to try doing it with fetch

Upvotes: 1

Views: 86

Answers (2)

Sarsa Murmu
Sarsa Murmu

Reputation: 447

This is the right way to do it using fetch().

fetch('content.php').then(res => {
  if (response.status !== 200) {
    console.log(`Looks like there was a problem. Status Code: ${response.status}`);
    return
  }

  res.text().then(text => {
    content.innerHTML = text
  })
})

Upvotes: 0

Tân
Tân

Reputation: 1

If you're using jquery, you can try to use .load() method:

$(content).load('content.php');

Or if you still want to use fetch method:

fetch('content.php')
    .then(function(response) {
        var html = response.text();

        var parser = new DOMParser();

        var doc = parser.parseFromString(html, "text/html");

        content.innerHTML = doc.innerHTML;
    });

Upvotes: 3

Related Questions