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

What is the method for accessing the req, res objects within the callback functions?

One of my preferences is to access the req, res, next objects outside of the middleware function. For instance, in a sample middleware file called sample.js: var app = express(); .... ..... .... var updateUserInput = { init:function(){ get_data ...

Troubleshooting Issue: ASP.NET UpdatePanel Not Responding to jQuery

I am having difficulties invoking jQuery functions within an "asp:UpdatePanel". Despite the code provided below, my attempts to add a class to the div element ".popup-body" are unsuccessful. Interestingly, the "alert();" function works without any issues. ...

Wcf Service does not define Angular JS methods

I am utilizing a WCF Service within an AngularJS application. The WCF Service is functional, and I am attempting to display a list of user records from a SQL database. However, upon running the application, I encountered the following errors: angular.js: ...

Issue with Jquery modal not functioning properly on second attempt

Currently, I am working on developing an application using CodeIgniter. However, I have encountered a problem where the modal window does not open for the second time. Here is a more detailed explanation of the issue: The form (view) in question contains ...

Troubleshooting issue with JavaScript sorting function failing to arrange elements in ascending

I'm having trouble sorting numbers in ascending order using JavaScript. Here's the code snippet: <h2>JavaScript Array Sort</h2> <p>Click the button to sort the array in ascending order.</p> <button onclick="myFunctio ...

What is the correct location to define the "env" setting in the eslint.config.js file?

In 2022, ESLint rolled out a new configuration system called the "flat config" here. Check out the documentation for the new "flat config". | Old configuration system documentation here. The "flat config" documentation shows that the `eslint.config.js` ...

What is the procedure for turning off hover color on an href element?

Working on a website that utilizes MUI components, I have incorporated href into the Tab elements within the navigation bar. <Tab label={element} id={index} sx={{display: {xs: 'none', md: 'inherit'}}} href={`#${navElements[element ...

Is using debounce with $scope.$apply a logical choice?

In my experience, I have come across a method that claims to decrease the number of $digest loops by incorporating debouncing into the $scope.$apply process. It looks something like this: $scope.$apply = _.debounce($scope.$apply, 250); Is this approach v ...

The observable did not trigger the next() callback

I'm currently working on incorporating a global loading indicator that can be utilized throughout the entire application. I have created an injectable service with show and hide functions: import { Injectable } from '@angular/core'; import ...

Prevent scrolling on browser resize event

I am working on a basic script that adds a fixed class to a specific div (.filter-target) when the user scrolls beyond a certain point on the page. However, I am wondering how I can prevent the scroll event from triggering if the user resizes their brows ...

Creating a unique styleset in styled-jsx using custom ruleset generation

TL;DR What's the best way to insert a variable containing CSS rules into styled-jsx (using styled-jsx-plugin-sass)? In my JSX style, I have the following: // src/pages/index.tsx ... <style jsx> {` .test { height: 100vh; width ...

What is the best way to sort and organize JSON data?

Upon successful ajax call, I receive JSON data structured like this: var videolist = [ { "video_id": 0, "video_name": "Guerrero Beard", "timelength": 15 }, { "video_id": 1, "video_name": "Hallie Key", "timelength": 8 }, { ...

When refreshing, the useEffect async function will not execute

Upon page load, the getImages function is intended to run only once. After refreshing the page, both tempQuestionImages and questionImages are empty. However, everything works perfectly after a hot reload. I am utilizing nextJs along with Firebase Cloud ...

JQuery syntax for adding a comma before the first element in an array

When I insert data into an array, the output in my console includes a comma before the first element (9). How can I remove this comma from the first element using the provided code snippet? ,9,My firstname,My lastname,<a href="/cdn-cgi/l/email-protecti ...

Is the Utilization of Inline JavaScript in HTML Attributes by Angular considered a "good practice"?

While going through the Angular tutorials, I found a lot to like. However, I couldn't help but wonder if "ng-click" is not essentially just an inline onClick function. My understanding was that the JavaScript community frowned upon using inline JavaSc ...

No output is displayed in the absence of errors. The program is functioning correctly

app.js angular.module('app', ['ionic', 'ui.router']) .config(('$urlRouterProvider', '$stateProvider', function($urlRouterProvider,$stateProvider){ $urlRouterProvider.otherwise('/'); $sta ...

Utilize JavaScript's $.post function to export PHP $_POST data directly into a file

After spending hours trying to figure this out, I've come to the realization that I am a complete beginner with little to no knowledge of what I'm doing... The issue I'm facing is related to some JavaScript code being triggered by a button ...

Is there a way to expand the clickable area of JQuery sliders?

Check out some of the jquery ui sliders here One issue I am facing is that when you click the slider bar, the tic jumps to that exact part. This can be problematic because the bar is quite thin, making it easy to miss when trying to click on it. I want to ...

Button click event not triggering JavaScript execution

I am experimenting with HTML, PHP and JS and have encountered a problem. Here is my code: <html> <head> <title> Dummy Code </title> <script> sendMail(){ <?php $to = '<a href="/cdn-cgi/l/email-protection" class ...

Tips for uploading numerous images to Firebase using React Native Fetch Blob

I have a collection of images stored in an array (image paths are stored in the array). I am trying to upload each image using a for loop, but only the last image gets uploaded. My approach involves using React Native Fetch Blob and Firebase for this task. ...