Create HTML Document with Custom URL for the document in JavaScript

In JavaScript, you can create an HTML document with a custom URL using document.implementation.createHTMLDocument() and the <base> element. This technique allows you to set a base URL that affects how relative URLs are resolved within the document.

How It Works

The createHTMLDocument() method creates a new HTML document. By adding a <base> element to the document's head, you establish a base URL that all relative URLs in the document will resolve against.

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Custom Base URL Example</title>
</head>
<body>
    <script>
        // Create a new HTML document
        const htmlDocument = document.implementation.createHTMLDocument();
        
        // Create a base element to set custom URL
        const customURL = htmlDocument.createElement('base');
        customURL.href = "https://www.tutorialspoint.com/java/index.htm";
        htmlDocument.head.append(customURL);
        console.log("Base URL=" + customURL.href);
        
        // Create an anchor element with relative URL
        const modifiedURL = htmlDocument.createElement("a");
        modifiedURL.href = "../java/java_questions_answers.html";
        htmlDocument.body.append(modifiedURL);
        console.log("After Modifying URL=" + modifiedURL.href);
    </script>
</body>
</html>

Output

Base URL=https://www.tutorialspoint.com/java/index.htm
After Modifying URL=https://www.tutorialspoint.com/java/java_questions_answers.html

Key Points

  • The <base> element must be placed in the document's <head> section
  • Only one <base> element should exist per document
  • Relative URLs in the document will resolve against the base URL
  • The base URL affects links, images, forms, and other resources with relative paths

Browser Compatibility

The createHTMLDocument() method is supported in all modern browsers including Chrome, Firefox, Safari, and Edge. The <base> element is part of the HTML standard and has universal browser support.

Conclusion

Using createHTMLDocument() with a <base> element provides a clean way to create HTML documents with custom base URLs. This approach is useful when dynamically generating content that needs specific URL resolution behavior.

Updated on: 2026-03-15T23:18:59+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements