Loading HTML fragments with jQuery


When I want to load a html fragment I prefer the contents of the container div in the page and the HTML fragment to have the same ID, like:


Master page

<!DOCTYPE html>
    <title>Master page</title>
    <!--Placeholder container. -->
    <div id="page"></div>

Page (html fragment)

<!DOCTYPE html>
    <title>Page (html fragment)</title>
    <!-- Page (html fragment to load). -->
    <div id="page"></div>


Then the following code can be used to replace the contents of the "placeholder" div, by the contents of the ”html fragment" div:



// Loads a html fragment.
// It replaces the content of the given DOM element, with the html fragment contents.
// It expects both the current page and the html fragment to contain the same "id" as the given id.
// Parameters:
// [id] example ["#page"].
// [url] example ["Features/Login/LoginView.html"].
function loadHtmlFragment (id, url)
    // Use jQuery "ajax" instead of jQuery "load", because "load" will get the whole div, 
    // when used with selector "#page" and not the contents.
    // You can get only the contents with "load", by using "url #page > *", 
    // but that will only get the child elements of the div, 
    // stripping out any direct child text.
        url: url,
        type: 'GET',
        dataType: "html",
        success: function (data)
            // Strip out any javascript by using "parseHtml".
            // Only use the contents of the html fragment by using "html()".
            var dom = $("<div>").append($.parseHTML(data)).find(id).html();

            // Adjust UI.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.