web – Embed Lines of HTML from a given file-ThrowExceptions

Exception or error:

Sorry if this is answered already, I couldn’t find the answer to this anywhere so help would be much appreciated.

I’m running a simple website with a bunch of very similar HTML files, each with the same group of clickable links which change depending on what I’m doing with the website.

If I need to add/remove/change a line of HTML, I need to do it similarly for each file.

I was wondering if there was an include type built into HTML where I can specify the varying lines in one file, and reference them into each HTML file so that I only need to change the reference file itself.

I know you can do this using JS, but is there any way using pure HTML?

Thanks.

How to solve:

Using pure HTML?

Yes, but… it almost certainly does not work the way you expect or need it to work. And you should not do this, given there are various much better alternatives.

What Not to Do

The <object> tag (see here) can be used – or, rather, mis-used. The problem is it will add your fragment as an embedded document, which means it will have a different context for layout, styling, scripting, and so on.

An example: I have a fragment of HTML in a file fragment.html:

<div class="stylish">hello world<div>

I have another file welcome.html containing a full HTML page:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>HTML object tag</title>
    <style>
        .stylish { color: magenta; }
    </style>
  </head>
  <body>
    <h2 class="stylish">demo</h2>

    <div class="stylish">
      <!-- don't do this! -->
      <object data="fragment.html"></object>
    <div>

  </body>
</html>

Specifically, note the <object data="fragment.html"></object> line.

Try this for yourself, and you will see that the fragment is indeed included. The “demo” heading is styled, but the “hello world” is not, despite my various attempts. This probably defeats your purpose.

This is a mis-use of the tag, anyway, as it is intended for use with multimedia objects.

Also, this tag can only be used in the body of an HTML page – not in the header (in case that was one of your requirements).

Older HTML tags such as <embed> and <iframe> have similar features.

So, Instead…

That brings you back to options discussed in other questions, such as this and this.

Leave a Reply

Your email address will not be published. Required fields are marked *