If you have an empty DOM document and need to add a `<head>` element dynamically using JavaScript, you can do so using the `document.createElement` method.
Adding a `<head>` to an Empty Document
If the document is completely empty (e.g., after `document.open()`), the DOM won’t have a `<head>` or `<body>`. You can add them like this:
```javascript // Ensure the document is empty before modifying document.open(); document.write("<!DOCTYPE html><html></html>"); // Creates a basic HTML structure document.close(); // Create and append <head> let head = document.createElement("head"); document.documentElement.prepend(head); // Adds <head> before <body> ```
Alternative: Check and Add `<head>` if Missing
If you’re unsure whether the `<head>` exists, this ensures it gets added:
```javascript if (!document.head) { let head = document.createElement("head"); document.documentElement.insertBefore(head, document.body || null); } ```
-> This checks if `document.head` exists.
-> If not, it inserts `<head>` before `<body>` or at the end of `<html>` if `<body>` is missing.
Why Would You Need This?
-> Manipulating an empty document (e.g., when dynamically writing HTML).
-> Ensuring metadata like `<title>` or `<meta>` can be added.
-> Working with iframes or dynamically generated pages.
Would you like an example where we add styles or scripts to the new `<head>`?