Home > Software engineering >  How to select only a div from another page with AJAX
How to select only a div from another page with AJAX

Time:03-10

I have a Social Media with posts, and I want to show the new with JS and AJAX. I tried to reload my page with AJAX and put it in a div element, but now the website is in this div element, so I have the full page twice. However, I only want to take the div element with AJAX. My code looks like this:

var timeout = setTimeout(loadDoc, 2000);

function loadDoc() {
  const xhttp = new XMLHttpRequest();
  xhttp.onload = function() {
    document.getElementById("container").innerHTML = this.responseText;
  }
  xhttp.open("GET", "mywebsite.com");
  xhttp.send();
  timeout = setTimeout(loadDoc, 2000);
}
<div id="container">
post2<br>
post1
</div>
Can someone help me?

Kind regards, ComputerJoshi

CodePudding user response:

There are two approaches you can take here:

Have a sensible API design

The URL you are requesting is returning a bunch of data you don't want.

Change it (or create a new URL to request instead) so that you only get the data you want.

You could keep that data in HTML form, but it is more typical to present it in a structured format (JSON is popular) and then use that to update the DOM of the current page.

Parse the HTML

Convert the string of HTML into a DOM (e.g. with DOMParser), then use querySelector to find the parts of that DOM you want and then copy them into the current DOM.

  • Related