0

I tried the following code. But it doesn't work properly. Only one file add/ include repetitively. How can I solve this? **I want to create a custom tag "" which can INCLUDE html file!!!! –

var createIncludeTag = document.createElement('include');
$(function(){
    var includeFile = $('include').attr('href');
    $("include").load(includeFile);		   
});
<include href="nav.html"></include>
<include href="main.html"></include>
<include href="footer.html"></include>

2
  • 1
    HTML does not have an include tag. Commented Mar 3, 2017 at 18:47
  • 1
    Possible duplicate of Load HTML template with JavaScript Commented Mar 3, 2017 at 19:02

2 Answers 2

2

<include> is not a valid html element.

You can use <link> element with rel attribute set to "import" to load resources into document. At load event of <link> element you can get the content of resource using link.import

<link rel="import" href="nav.html" type="text/html">

   $(function() {
     $("body").append($("link[href='nav.html']")[0].import.body.innerHTML)
   })

   $("link[href='nav.html']").on("load", function() {
     $("body").append(this.import.body.innerHTML)
   })

Alternatively, you can use .load()

   $("#element").load("nav.html");
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but I want more dynamic. I want to create a custom tag "<include>" which can INCLUDE html file!!!!
@Bapy <link> fetches resource, for example, an html document, which you can get using .import property at load event of <link> element. <include> is not a defined html element.
0

According to jquery API reference of .attr() function

Description: Get the value of an attribute for the first element in the set of matched elements.

That's why you only get the first include html loaded for all three elements.

You have to use .each() function instead.

<!DOCTYPE html>
<html>

<head>
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(function () {
            $("include").each(function (index, value) {
                $(this).load($(this).attr("href"));
            });
        });
    </script>
</head>

<body>
    <include href="nav.html"></include>
    <include href="main.html"></include>
    <include href="footer.html"></include>
</body>

</html>

By the way, creating a custom <include> TAG might not be a good idea.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.