1

I'm looking for a Javascript equivalent of a technique I've been using in PHP. That is, to place even the most basic page setup:

<!DOCTYPE html>
    <html lang="en">
        <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">

...in a php file like 'doc_start.php' and then start every page in my site with...

<?php require_once('/path/to/doc_start.php); ?>

Now I need to begin a project that's strictly HTML and JS (no PHP) and want a similar way to avoid duplicating basic, common HTML elements. Obviously, I want to do more than this very basic stuff, like import JQuery in every page, link to a common stylesheet, etc. Again, all easy in PHP, but I'm still kind of a newbie in JS.

I've read about HTML5 includes, but can't seem to find anything that addresses what I want to do

SherylHohman
  • 16,580
  • 17
  • 88
  • 94
curiojeff
  • 23
  • 1
  • 4
  • I disagree with the notion that this is a duplicate question. OP does *not* want to know how to include one JS file into another but how to include one part of an HTML document into another -- comparable to what PHP's `include` does, or templating engines. Don't always be so quick to close stuff! – typeduke Mar 28 '20 at 12:12

2 Answers2

0

Javascript and PHP are different languages for very different purposes. But assuming you have some element you don't want to repeat some elements one solution is the following:

Save the HTML elements that you don't want to keep repeating as a string. Then use the .innerHTML property to add elements.

The .innerHTML property stores the mark up of an element as a string.

For example, if we have the following <div>:

<div class="example"> <br> Hello there this is a test! </div>

...and we use .innerHTML:

console.log(document.querySelector(".example").innerHTML);

It will output "<br> Hello there this is a test!".

We can add to the .innerHTML using the += operator. So if you want to add something inside the body it's as simple as:

var something = "some HTML";
document.body.innerHTML += something;

Hope this was what you were looking for!

PolymorphismPrince
  • 307
  • 1
  • 4
  • 14
0

In order to import other pages into your current document, you need to use a link tag.

For example....

<head>
  <link rel="import" href="/path/to/imports/stuff.html">
</head>

This will allow you to reference other html, css or javascript documents into your page without copying and pasting the same code within each page.

https://www.w3schools.com/html/html_links.asp

Simone Anthony
  • 524
  • 6
  • 15