1

I am creating an HTML document and I want to embed an HTML snippet from a separate file (not a full HTML document) into it.

Suppose the document I want to embed into is the following:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <link href="style.css" rel="stylesheet">
</head>

<body>
(stuff)
<placeholder />
</body>
</html>

and the code to embed is this:

<h1>Hello world</h1>
<p>Lorem ipsum dolor sit amet, vel lucilius consequat adolescens ut, ex 
atomorum forensibus efficiendi mei. Eam adhuc regione eu, mei ex alia 
posidonium. Duis dicam postea mel id. Munere dolore ut eam, eam diam 
causae docendi id. At persius dolores eam, ea sea omnesque democritum, 
erroribus dissentiunt pro ut.</p>

Notice that the code I want to embed is not a complete HTML document; just a snippet. How would I embed that where the placeholder is in the main file using JavaScript?

SYZYGY-DEV 333
  • 145
  • 1
  • 2
  • 13
  • Where do you get the snippet from? – theonlygusti Oct 18 '16 at 20:02
  • Is the snippet already in a variable? – theonlygusti Oct 18 '16 at 20:03
  • jQuery allowed? – theonlygusti Oct 18 '16 at 20:05
  • 1
    Possible duplicate of [How do I load an HTML page in a
    using JavaScript?](http://stackoverflow.com/questions/17636528/how-do-i-load-an-html-page-in-a-div-using-javascript)
    – Adjit Oct 18 '16 at 20:05
  • @Adjit, this is not a duplicate. I am not loading a page; only a snippet, and I have no interest in loading it in a
    .
    – SYZYGY-DEV 333 Jan 20 '17 at 23:49
  • @SYZYGY-DEV333 Not the same question per se, but the same methods are applied. You don't need to load it into a `
    ` that is personal preference. Regardless, if you read all of the answers in that question you will find the same answer that was posted and marked correct here. You clearly have no interest in reading either.
    – Adjit Jan 23 '17 at 17:34

1 Answers1

2

If you are accepting a solution, this task becomes trivial:

$('placeholder').load('path/to/file.html');

Using jQuery#load to get a local file (path/to/file.html) and put its contents into the placeholder element.

Read more about jQuery selectors here, but know that jQuery will generally accept all CSS selectors with some modifications.


If jQuery is not an option, then there is still a fairly succinct way to accomplish this in "vanilla" javascript using XMLHttpRequests:

function loadFileIntoElement(filePath, elementSelector) {
  var request = new XMLHttpRequest();
  request.addEventListener("load", function() {
    var fileContents = this.responseText;
    document.querySelector(elementSelector).innerHTML = fileContents;
  });
  request.open("GET", filePath);
  request.send();
}

loadFileIntoElement('path/to/file.html', 'placeholder');

document.querySelector should also accept all valid CSS selectors.

theonlygusti
  • 11,032
  • 11
  • 64
  • 119