9

What would be the native javascript equivalent to the jquery below?

$('#anyDiv').load("anyPage.htm");
1

3 Answers 3

11

Yes, there is:

function load(target, url) {
  var r = new XMLHttpRequest();
  r.open("GET", url, true);
  r.onreadystatechange = function () {
    if (r.readyState != 4 || r.status != 200) return;
    target.innerHTML = r.responseText;
  };
  r.send();
}

load(document.getElementById('anyDiv'), 'anyPage.htm');
Sign up to request clarification or add additional context in comments.

1 Comment

Not sure what issue you are having, but it does work. See this fiddle (had to switch to POST to use jsfiddle's XHR endpoints). jsfiddle.net/rddw5eac
10

You can try this,

window.onload = () => {
    fetch('/path/to/page.html')
    .then(data => {
      return data.text()
    })
    .then( data => {
      document.getElementById("parentContainer").innerHTML = data;
    })
}

Comments

-1

You can try like this.

document.getElementById("anyDiv").innerHTML='<object type="text/html" data="anyPage.html" ></object>';

4 Comments

I can get the page to load with this but all the CSS that originally worked with the jquery script now doesn't work. CSS that was used in the "anyPage.htm" now appears broken....or maybe its the "<object>" container that needs CSS. Any suggestions?
Yes <object> tag needs CSS. Try something like this cssfile=http://www.yoursite.com/site1.css" inside your <object> tag. For more information refer this link htmlforums.com/html-xhtml/…
Apparently there is a limitation with the <object> tag....It will render with a scroll bar...I couldn't get to turn it off. I was hoping for a simple native JavaScript equivalent....but it is appearing that jquery's .load() is a hard to beat in all aspects.
Just a follow up. I have been able to use this method successfully. The only thing different is that I need ("anyPage.htm") to load its own CSS. Kind of like how an iframe behaves. And even if your object is within your site, I found it better to have a separate CSS file for the loaded objects.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.