If you want to print HTML like <h1>Welcome</h1> on a web page using JavaScript, here are the common ways.
Method 1: Using innerHTML (Most Common)
HTML
<div id="app"></div>
JavaScript
document.getElementById("app").innerHTML = "<h1>Welcome</h1>";
Output
<h1>Welcome</h1>
Method 2: Store HTML in a Variable
HTML as Variable
let html = "<h1>Welcome</h1>";
document.getElementById("app").innerHTML = html;
Method 3: Create the Element (Recommended)
const h1 = document.createElement("h1");
h1.textContent = "Welcome";
document.body.appendChild(h1);
Method 4: Using Template Literals (for Multiple Lines)
const html = `
<h1>Welcome</h1>
<p>This is a paragraph.</p>
`;
document.getElementById("app").innerHTML = html;
Which method should you use?
innerHTML→ Good for inserting HTML strings.createElement()→ Best practice when creating elements dynamically because it’s safer and easier to manipulate.- Template literals → Best for larger HTML blocks.