replilian replilian - 2 months ago 6
HTML Question

Can I import only a piece of html from an external file?

I need to create an html file that contains only content within a form tag of another html file, and nothing else. Is there any way to do this?

Answer

You can dynamically load html snippets after your main page loads using javascript. Something like this:

main.html

<html>
    <head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
        <script src="script.js"></script>
    </head>
    <body>    
        <h1>Form</h1>
        <div id="container"></div>
    </body>
</html>

form.html

<form>
    <input value="testing" />
</form>

script.js

var formUrl = 'form.html';

$(window).on('load', function(){
  $.get(formUrl, function(res){
     $('#container').append($(res));
  })
})

Here is a working plunk