create a document in javascript

To create a document in JavaScript, first, we need to create a new HTML document using the createElement() method, then we can add elements to it using the appendChild() method. Finally, we can add text to the elements using the innerHTML property.

Here is an example code snippet to create a new document with a h1 and a p element:

index.tsx
// Create a new HTML document
const newDoc = document.createElement('html');

// Create a new head and body element
const newHead = document.createElement('head');
const newBody = document.createElement('body');

// Create a new h1 element and add it to the body
const newH1 = document.createElement('h1');
newH1.innerHTML = 'Hello World';
newBody.appendChild(newH1);

// Create a new p element and add it to the body
const newP = document.createElement('p');
newP.innerHTML = 'This is a new document created with JavaScript';
newBody.appendChild(newP);

// Add the head and body to the new document
newDoc.appendChild(newHead);
newDoc.appendChild(newBody);

// Output the new document to the console
console.log(newDoc);
722 chars
24 lines

In this example, we first create a new HTML document using createElement('html'). Then we create new head and body elements using createElement(), and we add them to the html element using appendChild().

Next, we create a new h1 element and set its innerHTML to 'Hello World'. We add this element to the body element using appendChild(). Similarly, we create a new p element and add it to the body.

Finally, we add the head and body elements to the html element using appendChild(), and output the new document to the console using console.log().

gistlibby LogSnag