Horje
How to Load an HTML File into Another File using jQuery?

Loading HTML files into other HTML files is a common practice in web development. It helps in reusing HTML components across different web pages. jQuery is a popular JavaScript library, that simplifies this process with its .load() method.

Approach 1: Basic Loading with .load() Method

The .load() method in jQuery is used to load data from the server and place the returned HTML into a specified element.

HTML
<!-- index.html -->
<!DOCTYPE html>
<html>

<head>
    <title>Load HTML File</title>
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
    </script>
</head>

<body>
    <div id="content"></div>

    <script>
        $(document).ready(function () {
            $("#content").load("content.html");
        });
    </script>
</body>

</html>
HTML
<!-- content.html -->
<h1>GeeksforGeeks</h1>

<p>A computer science portal for geeks</p>

Output:

load-file-jquery

Explanation:

  • The <div> with id=”content” is the placeholder where the external HTML will be loaded.
  • The .load(“content.html”) method fetches the content of content.html and inserts it into the #content div.

Loading Specific Content

You can load specific parts of an HTML file by using a CSS selector after the file name in the .load() method.

HTML
<!-- index.html -->
<!DOCTYPE html>
<html>

<head>
    <title>Load Specific Content</title>
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
    </script>
</head>

<body>
    <div id="specific-content"></div>

    <script>
        $(document).ready(function () {
            $("#specific-content").load("content.html #container");
        });
    </script>
</body>

</html>
HTML
<!-- content.html -->
<h1>
    How to Load an HTML File into 
    Another File Using jQuery?
</h1>

<div id="container">
    <h1>GeeksforGeeks</h1>

    <p>A computer science portal for geeks</p>
</div>

Output:

load-file-jquery

Explanation: The .load(“content.html #container”) method fetches only the content within the element with id=”paragraph” from content.html.




Reffered: https://www.geeksforgeeks.org


JQuery

Related
What is Ajax ? What is Ajax ?
What is jQuery ? What is jQuery ?
How to Wrap an Element with Another Div Using jQuery? How to Wrap an Element with Another Div Using jQuery?
How to get the Day of the Week in jQuery ? How to get the Day of the Week in jQuery ?
Linkify jQuery Linkify jQuery

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
17