Writing HTML

Lesson 5
Author : Afrixi
Last Updated : March, 2023
Javascript - Program the Web
This course covers the basics of programming in Javascript.

In JavaScript, you can use the document.write() method to write HTML code directly to the web page. Here’s an example:


document.write("<h1>Hello, world!</h1>");

This code will write the “Hello, world!” header to the page when it is executed.

However, using document.write() to generate HTML is generally not recommended because it can cause issues with page loading and rendering. It is better to use the Document Object Model (DOM) to create and manipulate HTML elements in a more structured and efficient way.

Here’s an example of how you could use the DOM to create an h1 element and add it to the page:

// Create an h1 element
var header = document.createElement("h1");
// Set the text content of the header
header.textContent = "Hello, world!";
// Find the body element of the page
var body = document.querySelector("body");
// Add the header to the body
body.appendChild(header);

This code will create an h1 element, set its text content to "Hello, world!", find the body element of the page using document.querySelector(), and add the header to the body using the appendChild() method.