I need the equivalent of .load() to JS

22,573

Solution 1

UPDATE:

Using Fetch API with .then()

function load(url, element)
{
    fetch(url).then(res => {
        element.innerHTML = res; 
    });
}

Old XMLHttpRequest

function load(url, element)
{
    req = new XMLHttpRequest();
    req.open("GET", url, false);
    req.send(null);
    
    element.innerHTML = req.responseText; 
}

Usage

load("x.html", document.getElementById("b"));

Solution 2

If you want to do it without JS, I think this will help you, add this inside #b

<iframe src="x.html"></iframe> 

Solution 3

UPDATE:

Using Fetch API with .then()

function load(url, element)
{
    fetch(url).then(res => {
        element.innerHTML = res; 
    });
}

Old XMLHttpRequest

function load(url, element)
{
    req = new XMLHttpRequest();
    req.open("GET", url, false);
    req.send(null);
    
    element.innerHTML = req.responseText; 
}

Usage

load("x.html", document.getElementById("b"));

This will load "x.html" and put it inside the element.

Share:
22,573

Related videos on Youtube

Admin
Author by

Admin

Updated on July 24, 2020

Comments

  • Admin
    Admin over 3 years

    I'm developing a script but I mustn't use jQuery library so I need the equivalent of .load() in JS.

    I need to do this without jQuery:

    $(document).ready(function(){
    
    $('#a').click(function(){
       $('body').append('<div id="b"></div>')
       $('#b').load('x.html')
    });
    
    });
    

    Thanks!

    • Ben McCormick
      Ben McCormick over 10 years
      "I need to do this without JS" I assume you mean without jQuery?
  • eeadev
    eeadev over 8 years
    what if I want the async version of this function?
  • Akshay Gaur
    Akshay Gaur about 5 years
    Could you maybe expand on your answer? Or maybe write a short snippet that shows what you are trying to say here?
  • g-otn
    g-otn almost 5 years
    @eeadev, It's async by default, so you can simply remove the false from req.open() or change it to true. See XMLHttp​Request​.open()
  • Danial
    Danial almost 3 years
    note that jquery load will execute js on the loaded page (just like you loaded a page into a frame), whereas just setting the html will not

Related