Is it possible to retrieve specific elements from another html file using AJAX?

Looking to use vanilla JS for loading content dynamically without needing a page refresh. The goal is to retrieve content from another HTML file when a menu option is selected, while targeting either the body or a specific class.

Is it possible to achieve this without relying on jQuery?

Thank you in advance!

var AJAX = function(page){

  var request = new XMLHttpRequest();

  request.open("GET", page);

  request.send();

  request.addEventListener("load", function(response){
    console.log(response.target.responseText); // Currently displaying all HTML as text, but desire to extract either the body or a particular class and utilize it within an innerHTML method.
  });
}

Answer №1

Working with XMLHttpRequest makes handling responses easy - by setting the responseType to document, you can access the response document through the .response property of the instantiated XMLHttpRequest. This allows you to apply standard DOM methods on it. To illustrate, the code snippet below demonstrates how to retrieve and display the text content of the first element with a class name of foo from the response document:

function fetchData(url){
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  xhr.responseType = 'document';
  xhr.onload = function () {
    if (xhr.readyState !== 4 || xhr.status !== 200) return;
    
    // Handle error statuses
    
    // Accessing the response as a document
    const documentResponse = xhr.response;
    console.log(documentResponse.querySelector('.foo').textContent);
  };
  xhr.send();
}

If utilizing the more contemporary fetch method, you will need to explicitly convert the response text into a document, which can be achieved using DOMParser. Here's an example:

function fetchData(url){
  fetch(url)
    .then(response => response.text())
    .then((text) => {
      const documentParsed = new DOMParser().parseFromString(text, 'text/html')
      console.log(documentParsed.querySelector('.foo').textContent);
    });
}

An appealing feature of DOMParser is its versatility in converting any valid HTML string into a document.

Answer №2

There are two ways to accomplish this:

  1. Hide the content in a div and then access it through DOM manipulation.
  2. Parse the response as XML and interact with the tags.

Method 1:

ajaxRequest.onreadystatechange = function() {

           if(ajaxRequest.readyState == 4) {
              var ajaxDisplay = document.getElementById('ajaxDiv');
              ajaxDisplay.innerHTML = ajaxRequest.responseText;
           }
        }

For Method 2, this resource may be useful:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering a JSON_PARSER_ERROR when trying to call Google FCM using MobileFirstAdapter JS

I am working on integrating Google FCM Api for sending Push Notifications. Below is the snippet of code from my JavaScript file: function sendNotificationToUser() { var request={ path :'/fcm/send', method: 'POST&ap ...

Directive customization through comprehension expressions

Python is where I spend a lot of my time, so I'm really drawn to the comprehension_expression syntax within Angular's ngOptions. However, I would love to see this syntax extend to other inputs, such as with an ng-list. For instance, let's s ...

Managing extensive amounts of data with server-side scripting in a Datatable

I am exploring the use of the datatable plugin to effectively manage a large amount of data. Currently, I am interested in implementing "server side processing in datatables" with the help of server-side scripting. Since I have limited experience with AJA ...

I find the JSX syntax to be quite perplexing

While examining some code, I came across the following: const cardSource = { beginDrag(props) { return { text: props.text }; } }; When working with JSX block code or building objects, I usually use {}. The cardSource variable in this co ...

The e2e Protractor test is unable to identify the Angular component within a complex Angular router with multiple layers

I am currently working on an Angular application and I need to set up end-to-end testing for this project. Angular Package: 4.6.6 Protractor: 5.3.0 In addition, my project includes a multi-layer router that wraps the router-outlet into another component ...

Discover a method to conceal an element within a <div> by monitoring mouseover events in a separate <div> container

<div id="one-id"> <div id="some">Information</div> <div id="control"> <div id="value-1"> <img id="image-one-id" /> <img id="image-two-id" /> ...

What is the abbreviated term for personalized elements in React Native development?

After discovering that custom components can be created like this: const CustomComp=()=>{ console.log('Created custom comp'); return(<View></View>); } export default function App(){ return(<View style={{flex:1}}> &l ...

The "else" statement is never being executed

Trying to create a form where users enter their first name, last name, and city. If any input is empty or contains numbers, a message should appear requesting to fill out all boxes without numbers. Otherwise, display a personalized quote using the input in ...

Troubleshooting: Issue with running npm start | React app not loading

npm start command seems to be stuck at this particular point - The application is failing to load because of this issue. Here is the content of package.json file - { "name": "reacttest", "version": "0.1.0", & ...

What is the process for loading a .x model in Three.js?

Could anyone provide guidance on how to successfully load an animated .x model in Three.js? I am currently struggling with the process and have attempted to convert the .x model to collada without success. Unfortunately, my search for a free program to c ...

Another approach to utilize JavaScript for populating content into a <div> container?

Upon loading the page, I aim to display a message in the <div> element. Below is the HTML and JavaScript code I have implemented: <body onload="printMsg()"> <div id="write"></div> </body> function printMsg() { var no ...

Encountered an error while attempting to insert a new user into a MySQL database using the Node, Express, and MySQL package

Currently in the process of creating a CRUD API using NodeJS. My main goal at the moment is to execute a POST request to add a new user to the database. The issue I am facing is that although I can successfully add a new user to the database, my server cra ...

Choose the DIV element based on its data attribute using JSON

When using each(), my goal is to: Hide all divs where the data-infos.grpid = $jQuery(this).data('infos').grpid Show the next div where data-infos.ordre = $jQuery(this).data('infos').next_ordre I am unsure how to apply a "where" ...

Learn how to send data from a MySQL server to a Node.js application using Socket.IO

I've been facing a challenge recently. I am attempting to listen for events from the @rodrigogs/my-sql events node package and then emit those events through socket-io to the react client. However, there seems to be a disconnect that I can't see ...

Modifying the content of a paragraph by incorporating information from various sources

I need a way to input measurements for my items in text fields, and then with the click of a button, transfer those measurements into a paragraph in corresponding fields. The code I am currently using is shown below: <!DOCTYPE html> <html> & ...

Tips on converting a Java regular expression to JavaScript regular expression

Can someone assist me in translating the Java Regex code below to JavaScript Regex? (\\\p{Upper}{2})(\\\d{2})([\\\p{Upper}\\\p{Digit}]{1,30}+) I attempted using the following JavaScript Regex: ...

Utilize Chrome storage instead of localstorage to generate Parse sessions

I'm currently developing a Chrome Extension that relies on Parse User sessions. Because localstorage is limited to specific domains, I am looking to utilize chrome.storage so the data can be accessed across any site. The existing Parse Javascript SDK ...

Utilize vuex v-model to define the value of an object component

Coordinating input elements with object keys in Vuex state is my current challenge. Imagine I have this object: myObj: { foo: 1, bar: 2 } Within a component, I have a computed property set up like so: myObjVals: { get(){ return this.$store.state.myObj ...

"Scraping tool unable to make successful POST request via ajax, despite successful execution in Postman

I've been working on a scrapy spider to crawl a real estate website that includes listings for properties. The specific challenge I'm facing is retrieving the telephone number of the real estate agent, as it requires an AJAX post request. Strange ...

Angular's FormGroup for reactive forms is a powerful feature that allows for

Why am I unable to type in the input field before setting a value? html <form action="" [formGroup]="titleForm"> <input class="note-title" type="text" formControlName="title"> </form> ...