1

Ive been looking for a way to insert HTML from an another HTML file (saved locally) - But important without Jquery or other libraries. Basically what I am trying to do is refactor from this:

First Approach (is working)

public setForm(): void {
        this.appDiv.innerHTML = `<form id="registerForm">
        <h1 class="h3 mb-3 font-weight-normal">Please sign up</h1>
    <label for="inputEmail" class="sr-only">Email address</label>
    <input type="email" id="inputEmail" class="form-control" placeholder="Email address" required="" autofocus="">
    <label for="inputPassword" class="sr-only">Password</label>
    <input type="password" id="inputPassword" class="form-control mt-1" placeholder="Password" required="">
    <button id="registerButton" class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>`;
    }

to something like this:

Refactored version

public setForm(): void {
    this.appDiv.innerHTML = document.insertFromPath('./views/register-panel.html').innerHTML;
}

Why do I want to do this?

Not only that the code looks cleaner. It allows me to encapsulate logik and each file has its own "responsibility". Javascript files tend to get messy.^^

3
  • 1
    I am not able to find any method called insertFromPath over here: developer.mozilla.org/en-US/docs/Web/API/Document#Methods Where did you get that from? Commented Sep 7, 2018 at 13:46
  • 1
    This is just a suggestion.^^ Maybe I should mention this. But maybe there is a method along those lines. Commented Sep 7, 2018 at 13:47
  • so you're trying to create a templating engine? like pug or ejs? If you're doing this for fun and learning then I'd find resources on how to do this on google, if you're trying to actually get work done, just use an existing templating engine because those take a long time to create Commented Sep 7, 2018 at 13:47

3 Answers 3

1

You could use the object tag.

<object data="/views/register-panel.html"> 
    Your browser doesn’t support the object tag. 
</object>

NOTE: I have used the filepath you have provided. Please ensure your filepath is correct by checking your project structure.

Sign up to request clarification or add additional context in comments.

1 Comment

Even though your approach is working I feel like the loading is slow in comparison to my first approach and the linked html is not applying css classes...
1

Try this solution and use your ID instead of content

function setForm() {
     document.getElementById("content").innerHTML='<object type="text/html" data="/views/register-panel.html" ></object>';
}

Comments

0

If you want to make your .js cleaner, you can set a template in your html and consume it with Javascript.

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.