7

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

$('#anyDiv').load("anyPage.htm");
MarkL
  • 199
  • 1
  • 2
  • 7
  • 1
    http://stackoverflow.com/questions/3972880/how-to-create-dom-object-from-html-page-received-over-xmlhttprequest – Andreas Aug 21 '15 at 15:53

3 Answers3

10

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');
Rob M.
  • 35,491
  • 6
  • 51
  • 50
  • 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). https://jsfiddle.net/rddw5eac/ – Rob M. Aug 21 '15 at 18:33
8

You can try this,

window.onload = () => {
    fetch('/path/to/page.html')
    .then(data => {
      return data.text()
    })
    .then( data => {
      document.getElementById("parentContainer").innerHTML = data;
    })
}
Nikhil Singh
  • 1,486
  • 1
  • 13
  • 24
-1

You can try like this.

document.getElementById("anyDiv").innerHTML='<object type="text/html" data="anyPage.html" ></object>';
John R
  • 2,741
  • 2
  • 13
  • 32
  • 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 "" container that needs CSS. Any suggestions? – MarkL Aug 21 '15 at 16:26
  • Yes `` tag needs `CSS`. Try something like this `cssfile=http://www.yoursite.com/site1.css"` inside your `` tag. For more information refer this link http://www.htmlforums.com/html-xhtml/t-using-a-stylesheet-inside-an-object-tag-71466.html – John R Aug 21 '15 at 16:43
  • Apparently there is a limitation with the 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. – MarkL Aug 21 '15 at 17:56
  • 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. – MarkL Aug 04 '17 at 18:37