How to append an HTML to an existing file without using jQuery?

Is there a way to add the contents of one HTML file (the complete file including the tags and all) into a div? A way which uses pure JavaScript? Or is the only way to append lots of elements individually and make it a function maybe?

3 answers

  • answered 2017-12-11 09:18 nadun


      <h1>Put here your HTML content before insertion of b.js.</h1>
      <script src="customscript.js"></script>
      <p>And here whatever content you want afterwards.</p>


        <h1>Add your HTML code here</h1>\
         <p>Notice however, that you have to escape LF's with a '\', just like\
            demonstrated in this code listing.\

  • answered 2017-12-11 09:18 Robin Wright

    You can do this with ajax...but there is a catch. The HTML you load should not have <html> or <head> tags etc...

    Main page:

    <title>Ajax Wizardry</title>
      function ajax(requestedForm,target) {
        var xmlhttp;
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
          console.log("Content Updated");
        console.log("ajax status: "+xmlhttp.status);
          <input type='button' value='Ajax Magic' onclick='ajax(`stufftoloadintodiv.html`,`target_1`)' />
    <div id='target_1'></div>

    stufftoloadintodiv.html contents

    <p style='color:red;'>Hello World</p>

    What I have done here is create a function called 'ajax' that accepts 2 variables. The first is the path to the file you want to load, the second is the intended target element id. So if you had <div id='biscuits'></div> and you wanted to load the contents of 'digestive.html' then you would just need to call ajax('digestive.html','biscuits')

  • answered 2017-12-11 09:18 ZippyV

    One simple solution without javascript would be to reference file from an iframe. Using this approach you don't need to worry about the HTML structure of the file.